Class: HasInherited::InheritAccessor
- Inherits:
-
Object
- Object
- HasInherited::InheritAccessor
show all
- Defined in:
- lib/has_inherited.rb
Overview
Instance Method Summary
collapse
Constructor Details
#initialize(owner, assoc, heritage) ⇒ InheritAccessor
Returns a new instance of InheritAccessor.
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
|
# File 'lib/has_inherited.rb', line 41
def initialize(owner, assoc, heritage)
@owner = owner
@assoc = @owner.send(assoc)
if heritage.kind_of? Array
@parent = heritage.first
@parent_accessor = heritage.second
else
@parent = heritage
end
if @parent && @parent_accessor.nil?
if @parent.kind_of? Class
@parent_accessor = :global
else
@parent_accessor = :inheritable
end
end
end
|
Dynamic Method Handling
This class handles dynamic methods through the method_missing method
#method_missing(symbol, *args) ⇒ Object
119
120
121
122
123
124
125
126
127
128
|
# File 'lib/has_inherited.rb', line 119
def method_missing(symbol, *args)
name = symbol.to_s
if name =~ /=$/
self[name.gsub(/=$/, '')] = args.first
elsif name =~ /\?$/
!!self[name.gsub /\?$/, '']
else
self[name]
end
end
|
Instance Method Details
#[](attribute) ⇒ Object
60
61
62
63
64
65
66
67
|
# File 'lib/has_inherited.rb', line 60
def [](attribute)
attr_value = find_attr(attribute).try(:value)
if attr_value.nil? && has_parent?
return parent.__send__(:[], attribute)
else
return attr_value
end
end
|
#[]=(attribute, value) ⇒ Object
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
|
# File 'lib/has_inherited.rb', line 69
def []=(attribute, value)
attr = find_attr(attribute)
if value.nil?
attr.delete if attribute
else
if attr.nil?
if @owner.respond_to?(:new_record?) && @owner.new_record?
attr = @assoc.build(:name => attribute.to_s, :value => value)
else
attr = @assoc.create(:name => attribute.to_s, :value => value)
end
else
attr.update_attributes(:value => value)
end
end
end
|
#all(inherited = true) ⇒ Object
86
87
88
89
90
91
92
93
94
95
96
97
98
|
# File 'lib/has_inherited.rb', line 86
def all(inherited = true)
all_values = {}
@assoc.all.each {|ina| all_values[ina.name.to_sym] = ina.value}
if inherited
parent_proxy = parent
while parent_proxy
parent_proxy_hash = parent_proxy.__send__(:all, false)
all_values.reverse_merge! parent_proxy_hash
parent_proxy = parent_proxy.__send__(:parent)
end
end
all_values
end
|