Question

I have the following code below in my view:

<script type="text/javascript">    
  $(document).ready(function(){    
    $("#button").click(function(event){
      if(false) { //even with if (false), this code is still being executed!
        <% if obj %>
          <% my_method(obj) %>
        <% end %>
        $("#button").attr("href","/" + obj.my_path);
      }
    });        
  });
</script>

As you can see by the comment, the condition for the JavaScript if statement is false, so the block should never be executed. Yet for some reason it is like my JS does not exist and the ERB block is being called. Why is this happening? JS seems to work fine on other pages on the site.

If you need more info about this to help solve the problem ask away and I will try to provide as much information as I can.

Was it helpful?

Solution

You seem to be a bit confused about the difference between server-side and client-side code.

The ERB is executed on the server, the JavaScript on the client. When your ERB is being executed, Ruby pretty much sees this:

puts '<script type="text/javascript">'
puts '  $(document).ready(function(){'
puts '    $("#button").click(function(event){'
puts '      if(false) {'
if obj
  my_method(obj)
end
puts '        $("#button").attr("href","/" + obj.my_path);'
puts '      }'
puts '    });'       
puts '  });'
puts '</script>'

Simplifying a little bit more, the ERB boils down to something like this:

puts some_strings[0]
puts some_strings[1]
puts some_strings[2]
puts some_strings[3]
if obj
  my_method(obj)
end
puts some_strings[4]
puts some_strings[5]
puts some_strings[6]
puts some_strings[7]
puts some_strings[8]

When you unwrap the ERB, it becomes pretty obvious why my_method(obj) is being executed.

In ERB land, all your JavaScript is just a bunch of uninterpreted strings: your JavaScript is just a bunch of meaningless text until it gets to the client browser.

Then, the browser will see something like this:

<script type="text/javascript">    
  $(document).ready(function(){    
    $("#button").click(function(event){
      if(false) {
        $("#button").attr("href","/" + obj.my_path);
      }
    });        
  });
</script>

Your ERB is nowhere to be seen because it was handled on the server. But, your if(false) is seen and it will be interpreted by the client. However, your ERB has already run so the if(false) cannot affect your my_method(obj) Ruby call.

OTHER TIPS

The ERB code is Ruby code, it does not know anything about JavaScript and the if is just markup for it. If you don't want to have the ERB code executed fix the if inside the erb code, not on the JavaScript.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top