4

Why doesn't this work?

:javascript
    -[1,2,3].each do |number|
        $("#form_#{number}").my_method();

Rails gives me an error, saying that the variable number isn't defined.

2 Answers 2

6

The content of a filter isn’t interpreted as Haml. You can use #{...} for interpolation though, and that’s why you’re seeing the error – the filter sees the #{number} in "#form_#{number}", but the line above where number is defined is simply passed through as it is, not treated as Ruby, so as far as Ruby is concerned number is still undefined.

In this case you could do something like:

:javascript
    #{[1,2,3].map do |number|
        "$(\"#form_#{number}\").my_method();"
    end.join("\n")}

although that’s a bit unwieldy.

A clearer solution might be to create a helper method to create the javascript, which you could call from the filter:

def create_js(arr)
  arr.map do |number|
      "$(\"#form_#{number}\").my_method();"
  end.join("\n")
end

and the Haml would be

:javascript
    #{create_js([1,2,3])}
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks for the great explanation! Works well, except I wasn't able to get the .join("\n") trick to work on ruby 1.9.3 (the function above just returns the contents of arr)
@bevanb note I changed each to map as well as add the join; did you change that too? Otherwise, what do you see? (I’m using 1.9.3 and it works for me).
Ah, I missed the change from each to map, thanks for pointing that out.
0

You have ruby syntax within your javascript and that obviously will not work. You can use a library like underscore.js and iterate over your array like this:

_.each([1, 2, 3], function(number){
    $("#form_" + number).my_method();
});

Try that.

Or you can use jQuery's each:

$.each([1, 2, 3], function(i, number){
     $("#form_" + number).my_method();
});

1 Comment

Or, if the $() indicates jQuery, $.each([1,2,3],function(i, number) {...

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.