Created
February 13, 2014 03:15
-
-
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| //Empty space for binding constants | |
| MyApp.constants = { | |
| //You can even set it to nothing so you have intelli-sense in an IDE | |
| SECRET: null | |
| }; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <% content_for :head do -%> | |
| <%= ApplicationHelper.register_js_constant('SECRET', 'This works well') %> | |
| <% end -%> |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| //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