ruby-on-railsruby-on-rails-4routesbatman-rails

How do I route to a batman.js (batman-rails) controller in a rails 4 application without overwriting all other routes?


I already have an existing rails application that I want to keep, but I want to develop a part of it (1 controller with associated pages) using batman.js. I am succesfully able to and run the old rails application with batman-rails installed but problems start appearing when routing enters the picture.

The only way I have been able to display the batman-rails index.html page is by putting this line in routes.rb:

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

And then entering localhost:3000 in my browser. This however makes in impossible to view any other page from my application as they are all displayed blank (for example localhost:3000/store/index)

If i simply put:

get "batman/index"

in routes.rb all I get is a blank page when i go to localhost:3000/batman/index but all other pages work fine. In the console it seems like rails still makes the same request in both cases:

Started GET "/batman/index" for 127.0.0.1 at 2014-10-03 13:47:38 +0200
Processing by BatmanController#index as HTML
  Rendered layouts/batman.html.erb (8.1ms)
Completed 200 OK in 10ms (Views: 9.0ms | ActiveRecord: 0.0ms)

Since the first form of routing overrides all other redirects it is worthless since I want to be able to use the old application as is. How do I route to the batman-rails controller without overwriting all other routes?

TL:DR How do I route to a batman-rails controller in a rails 4 application without overwriting all other routes?


Solution

  • There are 2 decent options that I know of:

    1) Put the batman.js catch-all route after your existing routes. This will cause Rails to serve your existing routes normally, then fall back to batman.js only if there isn't another route. For example:

    # routes.rb
    
    # normal Rails route
    resources :store do
      resources :items
      resources :orders 
    end
    
    # batman.js catch-all route 
    get "(*redirect_path)" # etc...
    

    2) Namespace the batman.js application. Serve the batman.js app from a subpath of the app. You'll also have to set Batman.config.pathToApp, which tells batman.js to generate routes relative to the namespace.

    # routes.rb 
    
    # namespaced batman.js catch-all route 
    get "/batman_app/(*redirect_path)", to: "batman/index", constriants: lambda { |request| request.format == "text/html" }
    

    Also, tell batman.js to operate from this namespace

    # my_app.coffee
    Batman.config.pathToApp = "/batman_app"
    
    class @MyApp extends Batman.App 
      # ...