0

I have a controller#action that defines an instance variable:

@min_rating = 4

In the view I have the following:

<%= javascript_tag do %>
  min_rating = <%= @min_rating %>
<% end %>

Then in my Coffeescript I can do the following:

jQuery ->
  alert min_rating

And if I am on the page of that view, it works properly.

However, if I am on another view, I get a JS error saying that the var min_rating is not defined:

Uncaught ReferenceError: min_rating is not defined 

This is because I load all the JS for all the views in the application.js:

//= require_tree .

So, my question is: What is the best way to deal with this in Rails?

2
  • some one suggested me to use "//= require_self" or you can remove the entire statement //= require_tree . give it a try and update please Commented Aug 3, 2012 at 23:57
  • You might want to watch this house9.blogspot.com/2011/05/rails-31-javascript-execution.html - different options for executing javascript with rails assest pipeline / coffeescript Commented Aug 4, 2012 at 5:14

2 Answers 2

1

Since coffee script has no var statement it automatically inserts it for all variables in the coffee-script, that way it prevents the compiled JavaScript version from leaking everything into the global namespace.

So since there's no way to make something "leak" into the global namespace from the coffee-script side of things on purpose, you need to define your global variables as properties of the global object.

attach them as properties on window

<%= javascript_tag do %>
  window.min_rating = <%= @min_rating %>
<% end %>

and then access min_rating in your coffeescript.

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

Comments

0

It depends on your goals. One simple option is to check whether min_rating is defined in javascript before referencing it:

jQuery ->
  if typeof min_rating != 'undefined'
    alert min_rating

Or you can make sure that min_rating is defined on every page - possibly by moving that javascript_tag call to a decorator and falling back to a default value. Whether or not that makes sense for your application is up to you.

Or you could try to avoid loading the script that references on min_rating on pages where it is not needed. But that would mean that you would not be able to use the same combined javascript file on every page.

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.