Skip to content

Instantly share code, notes, and snippets.

@tastycode
Created June 23, 2014 17:14
Show Gist options
  • Save tastycode/9556e58bc616883b5c02 to your computer and use it in GitHub Desktop.
Save tastycode/9556e58bc616883b5c02 to your computer and use it in GitHub Desktop.
Common Constants
# 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