Module: Trust::InheritableAttribute::ClassMethods

Defined in:
lib/trust/inheritable_attribute.rb

Instance Method Summary collapse

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, options = {})
  src = "    def \#{name}=(v)\n      @\#{name} = v\n    end\n\n    def \#{name}\n      return @\#{name} unless superclass.respond_to?(:\#{name}) and value = superclass.\#{name}\n      @\#{name} ||= ::Trust::InheritableAttribute::deep_copy(value) # only do this once.\n    end\n  end_src\n  instance_eval src, __FILE__, __LINE__\n  if !options.key?(:instance_writer) || options[:instance_writer]\n    src = <<-end_src\n      def \#{name}=(v)\n        self.class.\#{name} = v\n      end\n    end_src\n    class_eval src, __FILE__, __LINE__\n  end\n  if !options.key?(:instance_reader) || options[:instance_reader]\n    src = <<-end_src\n      def \#{name}\n        self.class.\#{name}\n      end\n    end_src\n    class_eval src, __FILE__, __LINE__\n  end\nend\n"