Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why are the ActionView::Helpers::UrlHelper not available in the assets pipeline?

In ajax heavy applications having a javascript/coffeescript file that is aware of the routes in a rails application seems common and reasonable. Yet it is not easy access the url_for helper in your assets.

I commonly see people inline a variable in their views that the javascript reads. And there are a few plugins that make routes available via a javascript object. See Accessing rails routes in javascript.

Am I missing an easy way to do this? Is this a bad practice? What is the alternative?

like image 379
andynu Avatar asked Oct 29 '25 05:10

andynu


2 Answers

Because the standard way of using the pipeline is to compile the JS files to one file with a fingerpint, I don't think there is an alternative to doing this.

The URL helpers often require some sort of context in the form of variables or params. For example:

question_path(@current_question)

These are not going to be available when the JS files are compiled for production.

Passing in a generated path via a content block seems OK to me (I do it in a current app).

like image 75
Richard Hulse Avatar answered Oct 30 '25 21:10

Richard Hulse


Get the path from the view

The way we typically handle this is to have Javascript get any paths it needs from the HTML, which was rendered using all the view helpers.

For example, if you need to ajaxify a form, have the form's action attribute contain the correct URL for AJAX submission, and have Javascript look for it there.

like image 38
Nathan Long Avatar answered Oct 30 '25 22:10

Nathan Long