Route helpers in asset pipeline Route helpers in asset pipeline javascript javascript

Route helpers in asset pipeline


UPDATE: Now there is a gem that does this for you: js-routes


The problem is that Sprockets is evaluating the ERB outside of the context of your Rails app, and most of the stuff you're expecting isn't there.

You can add things to your Sprockets context like so:

Rails.application.assets.context_class.class_eval do  include Rails.application.routes.url_helpersend

That's all well and good, but getting the helpers that require an id to work is a little trickier. I'm going to use a technique called a URI Template:

var event_path = "<%= CGI.unescape event_path('{event_id}') %>";

which returns /events/{event_id} which you could render into a url using an object like { event_id: 1 }. See SugarJS's String#assign method as example implementation of this. You could also roll your own like I did.


You could move the file to views where it has access to the proper context, then pull it down to the client from a JS source tag. Referring to MyRailsApp::Application.routes.url_helpers may not be the best if you are writing an engine.