I am using Rails 3.2.12.
I would like to insert a ruby code in my asset JavaScript file:
function trim(string) {
return string.replace(/(^\s+)|(\s+$)/g, "");
}
function <%= controller_name %>() {
...
}
How can I do this?
Thanks in advance.
If variables you are going to pass are request-independent - then just give it a name *.js.erb.
For request-specific data (like controller name in your example) that's impossible. Javascript files are loaded independently from application requests and normally they are served as static assets by application server (apache, nginx). Thus if you want some custom script that is request-dependent put it inside your view template (.html.erb).
Also you can definitely proxy request to your js file through application (define it's route in routes.rb) but that will not be considered as good code.
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