views:

47

answers:

3

I want to set a global constant (in Rails) and then depending on that I want to put a condition in a JavaScript file (which is included in every page of my app). I also have some Rails dependent code based on this variable.

What is the best way to do this ?

+1  A: 

You can define a global variable like: window.profileName = 'Shikher';. Or in case you need several global variables I'd suggest to create a scope:

var Globals = {};
Globals.profileName = '<%= @user.profile_name %>';

and somewhere else

Globals.userId = '<%= @user.id %>';

In case you will use it everywhere you can insert the globals defenition right in the layout file.

fantactuka
A: 

you can use this gem http://github.com/ejschmitt/jsvars to define javascript vars via ruby and then use them in you js

hellvinz
+1  A: 

In application_controller.rb

def before_filter
  # This variable will be available in all controller actions and views
  @my_global = "testing" 
end

In application.html.erb

<script type="text/javascript">
  var my_global = "<%= @my_global %>"
</script>
fullware
This looks like the neatest way to do it... (I didn't try the gem way)Thanks!
Shikher