Skip to content

Instantly share code, notes, and snippets.

@jwietelmann
Created March 22, 2012 21:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jwietelmann/2164670 to your computer and use it in GitHub Desktop.
Save jwietelmann/2164670 to your computer and use it in GitHub Desktop.
Export data from Rails to JSON with optional namespacing
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