Sandro L
Sandro L

Reputation: 1160

How to make a global JavaScript File for Ruby on Rails 3which gets some content from Rails with <%= ... %>

I have a model with lots of parameters and a function giving all the parameter names. Now I'd like to have a global Javascript file using this function like this

function bar() {
    <% Model.parameter_names.each do |name|
       parameters.push("<%= name %>");
    <% end %>
    // do something with them
}

The *parameter_names* method is a Class Method (*def self.parameter_names*), so i do not need an object. Is this possible?

Upvotes: 0

Views: 1596

Answers (2)

Dominic Goulet
Dominic Goulet

Reputation: 8113

You can, sort of.

First of all, if you are thinking about a javascript file included like this :

<script src="your-js-file.js"></script>

You can forget about it. In no way, RoR is doing anything for that file.

You can mix javascript with RoR in controller responses because that js file is read by RoR, then evaluated for any Ruby expressions, then returned as the response to your browser. In fact, if you take a look at the js response from the controller for something like you wrote :

function bar() {
    <% Model.parameter_names.each do |name|
       parameters.push("<%= name %>");
    <% end %>
    // do something with them
}

you would see something like :

function bar() {
   parameters.push("abc");
   parameters.push("def");
   parameters.push("ghi");
   parameters.push("jkl");
}

Javascript is a client side technology. The only way to add server side code in it is to actually generate the js file with server side code. This is probably your best shot at it.

Controller :

def jsfile
    @variable = "hello, world!"
    respond_to do |format|
      format.js
    end
end

jsfile.js.erb

function bar() {
  alert('<%= @variable %>');
}

Include the javascript file like this :

<script src="<%= jsfile_controllername_path %>"></script>

And add the corresponding route in routes.rb

Upvotes: 2

Jeremy Weathers
Jeremy Weathers

Reputation: 2554

Create the Javascript array in the head of your layout and then reference that in your global JS file.

Layout example (HAML):

%html
  %head
    :javascript
      var parameter_names_array = ['#{Model.parameter_names.join(', ')}'];

Global JS file

function bar() {
  // do something with "parameter_names_array"
}

Upvotes: 2

Related Questions