Skip to content

Instantly share code, notes, and snippets.

@ajsharp
Created July 30, 2011 02:24
Show Gist options
  • Select an option

  • Save ajsharp/1115121 to your computer and use it in GitHub Desktop.

Select an option

Save ajsharp/1115121 to your computer and use it in GitHub Desktop.
require 'rubygems'
require 'json/pure'
require 'awesome_print'
class Person
attr_accessor :name, :age
def initialize(name, age)
@name, @age = name, age
end
def height
"5' 8\""
end
def family
[Person.new("Jane", 55), Person.new("Tom", 55)]
end
end
class Node
def initialize(object, &block)
@object = object
@result = {}
instance_eval(&block)
end
def render
@result
end
# Returns an array of key => value pairs
# May be called in multiple formats.
#
# @example Simple list of attributes
# attributes :name, :age, :height
#
# @example A dynamic attribute with explicit object context
# attribute(:isAdmin) { |obj| obj.is_admin? }
#
# @example Dynamic attribute (implicit context)
# attribute(:isAdmin) { is_admin? }
#
# @example Aliasing attribute names
# attributes :isAdmin => :is_admin?, :name, :age
#
def attributes(*attrs, &block)
attrs.each do |attr|
if block_given?
raise("Cannot pass block to #attributes with more than one argument") if attrs.size > 1
# explicit or implicit object context
@result[attr] = (block.arity > 0) ? block.call(@object) : @object.instance_eval(&block)
return nil
end
if attr.is_a?(Hash)
val = attr.values.first
attr_name = attr.keys.first
@result[attr_name] = @object.send(val)
else # simple attribute list
@result[attr] = @object.send(attr)
end
end
nil
end
alias :attribute :attributes
def collection(hash, &block)
key = hash.keys.first
things = hash.values.first
@result[key] = things.map do |thing|
self.class.new(thing, &block).render
end
end
end
class JSONEngine
attr_reader :tree
def initialize(template)
@tree = {}
instance_eval(template)
end
def to_json
JSON.generate(tree)
end
def to_hash
tree
end
def node(hash, &block)
name = hash.keys.first
object = hash.values.first
tree.merge!(name => Node.new(object, &block).render)
nil
end
end
template = <<-STR
alex = Person.new('alex', 25)
node :person => alex do
attributes :name, :age
attribute :height
attribute :idk => :age
attribute(:silly) { |person| person.age }
attribute(:billy) { age }
collection :family => alex.family do |member|
attributes :name, :age
attribute(:isOld) { true }
end
end
node :dude => alex do
attribute(:mass) { age * 4 }
end
STR
puts JSONEngine.new(template).to_json
# {
# "dude": {
# "mass": 100
# },
# "person": {
# "idk": 25,
# "silly": 25,
# "height": "5' 8\"",
# "billy": 25,
# "family": [{
# "name": "Jane",
# "isOld": true,
# "age": 55
# },
# {
# "name": "Tom",
# "isOld": true,
# "age": 55
# }],
# "name": "alex",
# "age": 25
# }
# }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment