Skip to content

Instantly share code, notes, and snippets.

@singpolyma
Last active August 29, 2015 14:05
Show Gist options
  • Select an option

  • Save singpolyma/d2de0ba53cf5e6ce9935 to your computer and use it in GitHub Desktop.

Select an option

Save singpolyma/d2de0ba53cf5e6ce9935 to your computer and use it in GitHub Desktop.
JSON Template
@model = OpenStruct.new(name: 'steve', age: 12, contacts: [{name: 'steve', sekret: 6}], other: 'stuff', moar: 'things')
json @model,
:name,
:age,
oldness: :age,
friends: [nested(:name), from: :contacts],
contacts: nested('contact_partial', :model)
other: ->(c) { c + 'hai' },
stuff: [->(c) { c + 'you' }, from: :moar]
json [@model],
this: :name
{people: (json [@model],
this: :name
)}
def get_or_map(k, v, object)
if v.respond_to?(:call)
v.call(object.public_send(k))
elsif v.is_a?(Array)
v.last.call(object.public_send(v.first))
else
object.public_send(v)
end
end
def nested(*args)
lambda do |*largs|
if largs.first.is_a?(String)
# Get partial and render
else
json(largs.first, *args)
end
end
end
def json(*args)
object = args.shift
object = OpenStruct.new(object) if object.is_a?(Hash)
if object.respond_to?(:map)
object.map { |x| json(x, *args) }
else
extra = args.last.is_a?(Hash) ? args.pop : {}
h = args.each_with_object({}) do |k, h|
h[k] = get_or_map(k, k, object)
end
extra.each_with_object(h) do |(k, v), h|
h[k] = get_or_map(k, v, object)
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment