Skip to content

Instantly share code, notes, and snippets.

@sabind
Created February 13, 2014 03:15
Show Gist options
  • Select an option

  • Save sabind/8969107 to your computer and use it in GitHub Desktop.

Select an option

Save sabind/8969107 to your computer and use it in GitHub Desktop.
Protect your JS variables in case someone copy's your script file. Additionally maintain a high level of re-use relying on application level configurations even in stock javascript files.
//Empty space for binding constants
MyApp.constants = {
//You can even set it to nothing so you have intelli-sense in an IDE
SECRET: null
};
class ApplicationHelper
def self.register_js_constant(key, value)
constant = "MyApp.constants.#{key.to_s}=#{value.to_json};"
"<script type=\"text/javascript\">#{constant}</script>"
end
end
<% content_for :head do -%>
<%= ApplicationHelper.register_js_constant('SECRET', 'This works well') %>
<% end -%>
//Access your server side variable
//It will be here when you need it (as long as the server appends it)
alert(MyApp.constants.SECRET);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment