Skip to content

Instantly share code, notes, and snippets.

@apeiros

apeiros/foo.rb Secret

Forked from rking/foo.rb
Created October 31, 2012 21:05
Show Gist options
  • Save apeiros/f33ccf72e1c21cea56c9 to your computer and use it in GitHub Desktop.
Save apeiros/f33ccf72e1c21cea56c9 to your computer and use it in GitHub Desktop.
#!/usr/bin/env ruby
class PropertyObject
@fields = []
def self.inherited(descendant)
descendant.initialize_fields
end
def self.initialize_fields
@fields = []
end
def self.fields
superclass.respond_to?(:fields) ? @fields+superclass.fields : @fields
end
def self.add_fields(*fields)
@fields.concat(fields)
attr_accessor *fields
end
def show
self.class.fields.each do |e|
p(__send__(e))
end
end
end
class PhysicalObject < PropertyObject
add_fields :length, :height, :width
end
class HeavyObject < PhysicalObject
add_fields :weight
end
ho = HeavyObject.new
ho.length = 1
ho.height = 2
ho.width = 3
ho.weight = 55
p PhysicalObject.fields # => [:length, :height, :width] (which is correct)
p HeavyObject.fields # => [:weight, :length, :height, :width, :weight])
ho.show # => should work
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment