Module: Trust::InheritableAttribute::ClassMethods
- Defined in:
- lib/trust/inheritable_attribute.rb
Instance Method Summary collapse
-
#inheritable_attr(name, options = {}) ⇒ Object
Creates an inheritable attribute with accessors in the singleton class.
Instance Method Details
#inheritable_attr(name, options = {}) ⇒ Object
Creates an inheritable attribute with accessors in the singleton class.
Derived classes inherit the attributes. This is especially helpful with arrays or hashes that are extended in the inheritance chain. Note that you have to initialize the inheritable attribute.
Example
class Cat
inheritable_attr :drinks
self.drinks = ["Becks"]
class Garfield < Cat
self.drinks << "Fireman's 4"
and then, later
Cat.drinks #=> ["Becks"]
Garfield.drinks #=> ["Becks", "Fireman's 4"]
62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 |
# File 'lib/trust/inheritable_attribute.rb', line 62 def inheritable_attr(name, = {}) src = <<-end_src def #{name}=(v) @#{name} = v end def #{name} return @#{name} unless superclass.respond_to?(:#{name}) and value = superclass.#{name} @#{name} ||= ::Trust::InheritableAttribute::deep_copy(value) # only do this once. end end_src instance_eval src, __FILE__, __LINE__ if !.key?(:instance_writer) || [:instance_writer] src = <<-end_src def #{name}=(v) self.class.#{name} = v end end_src class_eval src, __FILE__, __LINE__ end if !.key?(:instance_reader) || [:instance_reader] src = <<-end_src def #{name} self.class.#{name} end end_src class_eval src, __FILE__, __LINE__ end end |