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
48 49 50 51 52 |
# File 'lib/orange-core/magick.rb', line 48 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
54 55 56 57 58 59 60 61 62 63 |
# File 'lib/orange-core/magick.rb', line 54 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
65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 |
# File 'lib/orange-core/magick.rb', line 65 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
119 120 121 122 |
# File 'lib/orange-core/magick.rb', line 119 def cattr_accessor(*attributes) cattr_reader(*attributes) cattr_writer(*attributes) end |
#cattr_reader(*attributes) ⇒ Object
99 100 101 102 103 104 105 106 107 |
# File 'lib/orange-core/magick.rb', line 99 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
109 110 111 112 113 114 115 116 117 |
# File 'lib/orange-core/magick.rb', line 109 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 |