Created
March 22, 2012 21:23
-
-
Save jwietelmann/2164670 to your computer and use it in GitHub Desktop.
Export data from Rails to JSON with optional namespacing
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
class JsonHelper | |
# Usage: | |
# json_register("hello", "Hello, World!") | |
# json_register("foo.bar", @foobar) | |
def json_register(name, data) | |
@json_registry ||= {} | |
pieces = name.split('.') | |
last = pieces.pop | |
current = @json_registry | |
pieces.each do |p| | |
current[p] ||= {} | |
current = current[p] | |
end | |
current[last] = data | |
end | |
# I use json2.js for parsing, but you can use jQuery or whatever. | |
# Use this in a <script> tag on your application layout: | |
# Registry = JSON.parse('#{json_export_registry}'); | |
def json_export_registry | |
@json_registry.to_json | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment