Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails 3.1 insert ruby code in JavaScript file

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.

like image 402
Lesha Pipiev Avatar asked Feb 02 '26 04:02

Lesha Pipiev


1 Answers

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.

like image 120
Konstantin Rudy Avatar answered Feb 03 '26 18:02

Konstantin Rudy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!