Created
June 23, 2014 17:14
-
-
Save tastycode/9556e58bc616883b5c02 to your computer and use it in GitHub Desktop.
Common Constants
This file contains 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
# Share constants between ruby and javascript | |
# Setup | |
# (in application.html.erb, or some place to inject javascript) | |
# MyApplication.constants = #{CommonConstants.to_json}; | |
# | |
# Usage | |
# Ruby | |
# CommonConstants << "Math::PI" | |
# Javascript | |
# MyApplication.constants.MATH_PI | |
module CommonConstants | |
extend self | |
def to_json | |
Hash[constants.map do |const_name, value| | |
[json_name_for_const(const_name), value] | |
end].to_json | |
end | |
def constants | |
@constants ||= {} | |
end | |
def <<(const_name) | |
const_value = Object.const_get(const_name) | |
constants[const_name] = const_value | |
end | |
def json_name_for_const(const_name) | |
const_name | |
.split("::") | |
.map(&:underscore) | |
.map(&:upcase) | |
.join("_") | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment