Skip to content

Instantly share code, notes, and snippets.

@andrewrk
Created September 14, 2012 04:30
Show Gist options
  • Save andrewrk/3719780 to your computer and use it in GitHub Desktop.
Save andrewrk/3719780 to your computer and use it in GitHub Desktop.
class Parent
def render(args={})
expand = args[:expand] || {}
obj = { }
# how would we access child.fields here?
Parent.fields.each do |name, options|
prop = self.send(name)
obj[name] = if options[:model]
if (inner = expand[name])
prop.render(expand: inner)
else
{
id: prop.id
}
end
elsif options[:format] == :date
prop.utc.to_s
else
prop
end
end
obj
end
def self.show
puts @@fields.inspect
end
protected
def self.field(name, options={})
attr_accessor name
@fields ||= {}
@fields[name] = options
end
end
class A < Parent
field :hi, foo: 2
end
class B < Parent
field :boo, derp: 3
end
b = B.new
b.boo = "heyo"
# this line breaks because of the issue I am trying to solve
# test2.rb:6:in `block in render': undefined method `hi' for #<B:0x00000000c23fd0 @boo="heyo"> (NoMethodError)
puts b.render
puts "B fields"
puts B.show
puts "A fields"
puts A.show
puts "Parent fields"
puts Parent.show
# desired output:
# B fields
# {:boo => {:derp => 3}}
# A fields
# {:hi => {:foo => 2}}
# Parent fields
# {}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment