Skip to content

Instantly share code, notes, and snippets.

@warmwaffles
Created November 13, 2015 23:55
Show Gist options
  • Save warmwaffles/bd38e05a63a633c4b1fe to your computer and use it in GitHub Desktop.
Save warmwaffles/bd38e05a63a633c4b1fe to your computer and use it in GitHub Desktop.
require 'pp'
class Model
def initialize(args={})
set(args)
end
def set(attributes={})
return if attributes.nil? || attributes.empty? || !attributes.is_a?(Hash)
attributes.each do |k, v|
setter = "#{k}="
self.public_send(setter, v) if self.respond_to?(setter)
end
end
end
class Foo < Model
attr_accessor :id, :bar
end
class Qux < Model
attr_accessor :id, :baz
end
foos = [
Foo.new(id: 1, bar: 'abc'),
Foo.new(id: 2, bar: 'def')
]
quxs = [
Qux.new(id: 9, baz: '123'),
Qux.new(id: 8, baz: '456')
]
builder = Jbuilder.new do |json|
json.set!(:data) do
json.set!(:type, 'jbuilder-tests')
json.set!(:attributes) do
json.set!(:title, 'this is a test')
end
end
json.included do
json.array!(foos) do |foo|
json.set!(:id, foo.id.to_s)
json.set!(:bar, foo.bar)
end
json.array!(quxs) do |qux|
json.set!(:id, qux.id.to_s)
json.set!(:baz, qux.baz.to_s)
end
end
end
pp builder.target!
# {
# "data":{
# "type":"jbuilder-tests",
# "attributes":{
# "title":"this is a test"
# }
# },
# "included":[
# {"id":"1","bar":"abc"},
# {"id":"2","bar":"def"},
# {"id":"9","baz":"123"},
# {"id":"8","baz":"456"}
# }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment