3

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.

2
  • You can not directly insert ruby code in javascript file. You need to pass some parameters by ajax. Commented Jul 23, 2013 at 12:03
  • I think you should rework on the solution to pass data as variable instead :) Commented Jul 23, 2013 at 12:04

3 Answers 3

8

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.

Sign up to request clarification or add additional context in comments.

Comments

2

I believe if you have a javascript file with the extension .js.erb or .js.coffee.erb, all the extensions would be parsed from right to left, thus your code should understand some erb tags inside it, before parsing the coffeescript and ultimately the js part.

Comments

1

I'm not sure why you would want to use the controller name when DEFINING your function, but if you really do, then

ALTERNATIVELY,

You could predefine functions statically for each controller, e.g.:

  function Users(param1, param3...){
    ....   
  }
  function Friends(param1, param3...){
    ....   
  }
  function Likes(param1, param3...){
    ....   
  }
  function Posts(param1, param3...){
    ....   
  }

then add an additional JavaScript statement to launch the appropriate function depending on which controller is being called, e.g.:

  <%= controller_name %>();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.