Robert Mosolgo

To my knowledge, batman.js is not maintained. For that reason, I don't suggest that you use it for a new project!

Adding Batman.js to an Existing Rails App

I had an existing app, but I wanted to take the front end to the next level. Batman.js is a full-featured, developer-friendly, Rails-inclined CoffeeScript (or JavaScript) framework with powerful Rails integration.

Installing Batman.js

I was already using ActiveModel::Serializer to serve JSON from my app. To get Batman on the scene, I included batman-rails in my Gemfile and installed it:

Gemfile.rb
1
require 'batman-rails', '~> 0.15'
1
  $ bundle install

The batman-rails gem comes with a generator to get everything in order. I ran it and restarted my Rails server:

1
2
  $ rails g batman:app # that's not _your_ app name, it's just "app"
  $ powder restart # restart your Rails server one way or another

I visited my app’s root_url and found Batman-rails landing page. How’d it get there!? Sure enough, the Batman generator had added a punchy line to the top of my routes file:

config/routes.rb
1
  get "(*redirect_path)", to: "batman#index", constraints: lambda { |request| request.format == "text/html" }

It captures all text/html requests and passes them to BatmanController, which was also created by the generator:

app/controllers/batman_controller
1
2
3
4
5
  class BatmanController < ApplicationController
    def index
      render nothing: true, layout: 'batman'
    end
  end

Along with that, there was a new file in my app/views/layouts folder, and then of course, app/assets/batman.

My first view

I didn’t want the Batman landing page at my root_url, I wanted a list of sounds! So, I ran a Batman generator, beefed up the model and controller, created the index html, and redefined the route:

app/controllers/batman_controller
1
  $ rails g batman:scaffold Sounds
app/assets/batman/models/sound.js.coffee
1
2
3
4
5
6
7
8
9
class Lang.Sound extends Batman.Model
  @resourceName: 'sounds'
  @storageKey: 'sounds'

  @persist Batman.RailsStorage

  # Use @encode to tell batman.js which properties Rails will send back with its JSON.
  @encode 'letter'
  @encodeTimestamps()
app/assets/batman/controllers/sounds_controller.js.coffee
1
2
3
4
class Lang.SoundsController extends Lang.ApplicationController
  routingKey: 'sounds'
  index: (params) ->
    @set("sounds", Lang.Sound.get('all'))
app/assets/batman/html/sounds/index.html
1
2
3
4
5
<ul>
  <li data-foreach-sound="sounds">
    <span data-bind="sound.letter" />
  </li>
</ul>

your filename will be your app name:

app/assets/batman/lang.js.coffee
1
2
class Lang extends Batman.App
  @root "sounds#index"

And now I had my own landing page!