Module: FSR::Traited
- Defined in:
- lib/fsr/traited.rb
Overview
Traited helps you doing configuration similar to class variables.
It’s built on a simple Hash, where keys are objects and the values the configuration. By using #ancestral_trait you will get nicely inherited configuration, where keys later in the ancestors will take precedence.
Class Method Summary (collapse)
Instance Method Summary (collapse)
-
- (Object) ancestral_trait
Builds a trait from all the ancestors, closer ancestors overwrite distant ancestors.
- - (Object) ancestral_trait_values(key)
-
- (Object) class_trait
trait for self.class if we are an instance.
- - (Object) each_ancestral_trait(obj)
- - (Object) trait(hash = nil)
Class Method Details
+ (Object) included(into)
31 32 33 |
# File 'lib/fsr/traited.rb', line 31 def self.included(into) into.extend(self) end |
Instance Method Details
- (Object) ancestral_trait
Builds a trait from all the ancestors, closer ancestors overwrite distant ancestors
class Foo
include FSR::Traited
trait :one => :eins, :first => :erstes
end
class Bar < Foo
trait :two =&gt; :zwei
end
class Foobar < Bar
trait :three =&gt; :drei, :first =&gt; :overwritten
end
Foobar.ancestral_trait # => => :drei, :two => :zwei, :one => :eins, :first => :overwritten
65 66 67 68 69 |
# File 'lib/fsr/traited.rb', line 65 def ancestral_trait klass = self.kind_of?(Module) ? self : self.class ANCESTRAL_TRAITS[klass] ||= each_ancestral_trait({}){|hash, trait| hash.update(trait) } end |
- (Object) ancestral_trait_values(key)
71 72 73 74 75 76 |
# File 'lib/fsr/traited.rb', line 71 def ancestral_trait_values(key) klass = self.kind_of?(Module) ? self : self.class cache = ANCESTRAL_VALUES[klass] ||= {} cache[key] ||= each_ancestral_trait([]){|array, trait| array << trait[key] if trait.key?(key) } end |
- (Object) class_trait
trait for self.class if we are an instance
86 87 88 |
# File 'lib/fsr/traited.rb', line 86 def class_trait respond_to?(:ancestors) ? trait : self.class.trait end |
- (Object) each_ancestral_trait(obj)
78 79 80 81 82 83 |
# File 'lib/fsr/traited.rb', line 78 def each_ancestral_trait(obj) ancs = respond_to?(:ancestors) ? ancestors : self.class.ancestors ancs.unshift(self) ancs.reverse_each{|anc| yield(obj, TRAITS[anc]) if TRAITS.key?(anc) } obj end |
- (Object) trait(hash = nil)
35 36 37 38 39 40 41 42 43 44 45 |
# File 'lib/fsr/traited.rb', line 35 def trait(hash = nil) if hash TRAITS[self] ||= {} result = TRAITS[self].merge!(hash) ANCESTRAL_VALUES.clear ANCESTRAL_TRAITS.clear result else TRAITS[self] || {} end end |