0

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 ?

3 Answers 3

2

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>
Sign up to request clarification or add additional context in comments.

1 Comment

This looks like the neatest way to do it... (I didn't try the gem way) Thanks!
1

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.

Comments

0

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.