Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using a Rails helper method within a javascript asset

Is there any way to use a Rails helper method, more specifically, a path helper method within a javascript asset file. This file foo.js.coffee.erb

$('#bar').val("<%= create_post_path %>") 

I would love it if I could get from erubis

$('#bar').val("path/to/create") 
like image 981
axsuul Avatar asked Sep 17 '11 00:09

axsuul


People also ask

What is helper method in JavaScript?

Helper functions are JavaScript functions that you can call from your template. Ember's template syntax limits what you can express to keep the structure of your application clear at a glance. When you need to compute something using JavaScript, you can use helper functions.

Can we use helper method in controller rails?

In Rails 5, by using the new instance level helpers method in the controller, we can access helper methods in controllers.

How do you use the helper method in Ruby on Rails?

A Helper method is used to perform a particular repetitive task common across multiple classes. This keeps us from repeating the same piece of code in different classes again and again. And then in the view code, you call the helper method and pass it to the user as an argument.


2 Answers

You can include any helper/module/class in an erb template with:

<% environment.context_class.instance_eval { include MyHelper } %> 

See: https://github.com/rails/sprockets/blob/master/lib/sprockets/environment.rb and https://github.com/rails/sprockets/blob/master/lib/sprockets/context.rb

To use the url helpers you have to include your specific applications' helpers.

They are available at Rails.application.routes.url_helpers so:

<% environment.context_class.instance_eval { include Rails.application.routes.url_helpers } %> 

EDIT: Fixed links to moved sprockets repo but not really sure this still makes sense so many years later.

like image 167
eirc Avatar answered Oct 19 '22 21:10

eirc


This will also do the trick in an initializer:

Sprockets::Context.send :include, MyHelper 

In development mode the helper will not be reloaded on every request.

Your approach with UrlHelpers will work until you need to find post_path(...um...we don't know what post id we'll need at compile time...). There is a ruby gem which reimplements all of your Rails UrlHelpers in JavaScript: https://github.com/railsware/js-routes

like image 28
user1158559 Avatar answered Oct 19 '22 21:10

user1158559