Module: ClassInheritableAttributes
- Included in:
- Orange::Application, Orange::Carton, Orange::Plugins::Base, Orange::Resource
- Defined in:
- lib/orange-core/magick.rb
Overview
Borrowed from Roman2k: github.com/Roman2K/class-inheritable-attributes/
Class Method Summary collapse
- .eval_in_accessor_module(klass, code) ⇒ Object
- .fetch_value(klass, attribute) ⇒ Object
- .store_value(klass, attribute, value) ⇒ Object
Instance Method Summary collapse
- #cattr_accessor(*attributes) ⇒ Object
- #cattr_reader(*attributes) ⇒ Object
- #cattr_writer(*attributes) ⇒ Object
Class Method Details
.eval_in_accessor_module(klass, code) ⇒ Object
45 46 47 48 49 |
# File 'lib/orange-core/magick.rb', line 45 def eval_in_accessor_module(klass, code) mod = klass.instance_eval { @_inheritable_attribute_accessors ||= Module.new } klass.extend(mod) mod.module_eval(code) end |
.fetch_value(klass, attribute) ⇒ Object
51 52 53 54 55 56 57 58 59 60 |
# File 'lib/orange-core/magick.rb', line 51 def fetch_value(klass, attribute) each_parent(klass) do |parent| if values = registry[parent] and values.key?(attribute) return values[attribute] elsif parent.instance_variable_defined?("@#{attribute}") return parent.instance_variable_get("@#{attribute}") end end return nil end |
.store_value(klass, attribute, value) ⇒ Object
62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 |
# File 'lib/orange-core/magick.rb', line 62 def store_value(klass, attribute, value) if Thread.current == Thread.main if value.nil? klass.instance_eval do remove_instance_variable("@#{attribute}") if instance_variable_defined?("@#{attribute}") end else klass.instance_variable_set("@#{attribute}", value) end else registry[klass] ||= {} if value.nil? registry[klass].delete(attribute) registry.delete(klass) if registry[klass].empty? else registry[klass][attribute] = value end end end |
Instance Method Details
#cattr_accessor(*attributes) ⇒ Object
116 117 118 119 |
# File 'lib/orange-core/magick.rb', line 116 def cattr_accessor(*attributes) cattr_reader(*attributes) cattr_writer(*attributes) end |
#cattr_reader(*attributes) ⇒ Object
96 97 98 99 100 101 102 103 104 |
# File 'lib/orange-core/magick.rb', line 96 def cattr_reader(*attributes) attributes.each do |attribute| ClassInheritableAttributes.eval_in_accessor_module(self, <<-EOS) def #{attribute} #{ClassInheritableAttributes}.fetch_value(self, :#{attribute}) end EOS end end |
#cattr_writer(*attributes) ⇒ Object
106 107 108 109 110 111 112 113 114 |
# File 'lib/orange-core/magick.rb', line 106 def cattr_writer(*attributes) attributes.each do |attribute| ClassInheritableAttributes.eval_in_accessor_module(self, <<-EOS) def #{attribute}=(value) #{ClassInheritableAttributes}.store_value(self, :#{attribute}, value) end EOS end end |