So, Rails is ready, let’s get Batman talking. It turns out to be really easy.
First let’s run the generator that comes with batman-rails:
1
$ rails g batman:install
I’m not a fan of having things directly under javascripts so I moved the created directory structure so things are like: (copying a fresh Batman 0.9.0 install into place under lib):
window.BatmanRailsDemo = classBatmanRailsDemoextendsBatman.App@title = "Batman Rails Demo"# 0.8.0 changed to this syntaxBatman.ViewStore.prefix = 'assets/batman/views'@navLinks: [{href: "/#!/posts/",controller: "posts",text: "Posts"},]# routing...@resources'posts'@root'posts'# here and below is automatically generated@on'run',->console?.log"Running ...."@on'ready',->console?.log"BatmanRailsDemo ready for use."# flash is a simple object@flash: Batman()# when you set an message, it auto-expires@flash.accessorget: (key) ->@[key]set: (key, value) ->@[key]=valueifvalueisnt''setTimeout=>@set(key,''),2000value@flashSuccess: (message) ->@set'flash.success',message@flashError: (message) ->@set'flash.error',message
Most of that is boilerplate, but we can see that I added some Nav bits and that routing takes TWO LINES! It even looks like a Coffee-ized Rails. Neato. The ViewStore bit is really important. If you get errors from Batman saying it can’t find your views, it is either that line or missing asset pipeline gems.
classBatmanRailsDemo.PostsControllerextendsBatman.ControllerroutingKey: 'posts'index: (params) ->BatmanRailsDemo.Post.load(err,results)=>@set'posts',resultsshow: (params) ->@set'post',BatmanRailsDemo.Post.findparseInt(params.id,10),(err) ->throwerriferr@rendersource: 'posts/show'new:(params) ->@set'post',newBatmanRailsDemo.Post()@form = @render()create: (params) ->@get('post').save(err)=>$('#new_post').attr('disabled',false)iferrthrowerrunlesserrinstanceofBatman.ErrorsSetelseBatmanRailsDemo.flashSuccess"#{@get('post.title')} created successfully!"@redirect'/posts'edit: (params) ->@set'post',BatmanRailsDemo.Post.findparseInt(params.id,10),(err) ->throwerriferr@form = @render()update: (params) ->@get('post').save(err)=>$('#edit_post').attr('disabled',false)iferrthrowerrunlesserrinstanceofBatman.ErrorsSetelseBatmanRailsDemo.flashSuccess"#{@get('post.title')} updated successfully!"@redirect'/posts'# not routable, an eventdestroy: ->@get('post').destroy(err)=>iferrthrowerrunlesserrinstanceofBatman.ErrorsSetelseBatmanRailsDemo.flashSuccess"Removed successfully!"@redirect'/posts'
That is structured exactly like a resourceful controller in Rails (although destroy isn’t routable). Convenient. A Rails developer should look at this as the MVC they already know.