Module: Ancestree::ClassMethods

Defined in:
lib/ancestree.rb

Constant Summary collapse

@@inherit_ancestor_attributes =
[]

Instance Method Summary collapse

Instance Method Details

#create_inheritable_method(attribute) ⇒ Object



28
29
30
31
32
33
34
35
# File 'lib/ancestree.rb', line 28

def create_inheritable_method(attribute)
  name = attribute.to_s.gsub(/(\?|!)/, '')
  define_method "#{name}_with_parent#{$1}".to_sym do
    val = send("#{name}_without_parent#{$1}") || parent.try(attribute.to_sym)
    val ||= send("default_#{name}") if respond_to?("default_#{name}")
    val
  end
end

#inherit_ancestor_attributes(*attrs) ⇒ Object



19
20
21
22
23
24
25
26
# File 'lib/ancestree.rb', line 19

def inherit_ancestor_attributes(*attrs)
  self.define_attribute_methods
  attrs.each do |attr|
    create_inheritable_method(attr)
    @@inherit_ancestor_attributes << attr.to_sym
    method_added(attr) if method_defined?(attr)
  end
end

#method_added(name) ⇒ Object



37
38
39
40
41
42
# File 'lib/ancestree.rb', line 37

def method_added(name)
  if defined?(:@@inherit_ancestor_attributes) && @@inherit_ancestor_attributes.include?(name)
    @@inherit_ancestor_attributes.delete(name)
    alias_method_chain name, :parent
  end
end