Class: Famili::Child

Inherits:
BasicObject
Defined in:
lib/famili/child.rb

Instance Method Summary collapse

Constructor Details

#initialize(mother, attributes) ⇒ Child

Returns a new instance of Child.



3
4
5
6
7
8
# File 'lib/famili/child.rb', line 3

def initialize(mother, attributes)
  @mother = mother
  @attributes = attributes
  @unresolved_attribute_names = attributes.keys.dup
  @cached_attributes = {}
end

Instance Method Details

#[](name) ⇒ Object



10
11
12
# File 'lib/famili/child.rb', line 10

def [](name)
  resolve_attribute(name)
end

#bind(instance, &block) ⇒ Object



21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
# File 'lib/famili/child.rb', line 21

def bind(instance, &block)
  @instance = instance
  @resolve_callback = block
  @instance.instance_variable_set(:@__famili_child__, self)
  define_method_stub(:method_missing) do |name, *args|
    mother = @__famili_child__.__send__(:mother)
    if mother.respond_to?(name)
      mother.send(name, *args)
    elsif (value = @__famili_child__.__send__(:cached_attributes)[name])
      value
    else
      send(@__famili_child__.__send__(:munge, :method_missing), name, *args)
    end
  end
  @attributes.each { |attr_name, _| define_property_stub(attr_name) }
end

#resolve_attributes(instance = nil, &block) ⇒ Object



14
15
16
17
18
19
# File 'lib/famili/child.rb', line 14

def resolve_attributes(instance = nil, &block)
  bind(instance, &block) if instance
  resolve_attribute(unresolved_attribute_names.first) until unresolved_attribute_names.empty?
  unbind if instance
  instance
end

#unbindObject



38
39
40
41
42
43
# File 'lib/famili/child.rb', line 38

def unbind
  @resolve_callback = nil
  @attributes.each { |attr_name, _| undefine_property_stub(attr_name) }
  undefine_method_stub(:method_missing)
  @instance.send(:remove_instance_variable, :@__famili_child__)
end