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")
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.
In Rails 5, by using the new instance level helpers method in the controller, we can access helper methods in controllers.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With