Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Route helpers in asset pipeline

using Rails 3.1.0.rc4, I'm trying to access a route helper in a javascript file (event.js.erb in this case) and it seems like they are not loaded at that moment. When requesting the merged /assets/application.js file, I get:

throw Error("NameError: undefined local variable or method `events_path' for #<#<Class:0x00000001580010>:0x00000003191510>\n  (in /<...>/app/assets/javascripts/event.js.erb)") 

Any idea how to access the route helper in there?

like image 947
tbuehlmann Avatar asked Jul 17 '11 17:07

tbuehlmann


People also ask

What is a route helper?

A Route Driver Helper is responsible for safely and efficiently assisting in delivering, and unloading product sold to customers.

How do you Precompile an asset?

To compile your assets locally, run the assets:precompile task locally on your app. Make sure to use the production environment so that the production version of your assets are generated. A public/assets directory will be created. Inside this directory you'll find a manifest.

What is an asset pipeline?

1 What is the Asset Pipeline? The asset pipeline provides a framework to concatenate and minify or compress JavaScript and CSS assets. It also adds the ability to write these assets in other languages and pre-processors such as CoffeeScript, Sass, and ERB.

What does rake assets Clean do?

The clean it removes the old versions of the precompiled assets while leaving the new assets in place. Show activity on this post. rake assets:clean removes compiled assets. It is run by cap deploy:assets:clean to remove compiled assets, generally from a remote server.


1 Answers

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_helpers end 

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.

like image 148
Adam Lassek Avatar answered Oct 03 '22 08:10

Adam Lassek