/
attributes.rb
46 lines (37 loc) · 1.01 KB
/
attributes.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
module Glamazon
module Attributes
def method_missing(meth, *args, &blk)
add_attribute(meth)
meth.to_s =~ /\=$/ ? send(meth, args.first) : send(meth)
end
def to_s
attributes.inspect
end
def attributes
@attributes ||= {}
end
def [](attribute)
attributes[attribute.to_s]
end
def []=(attribute, value)
attributes[attribute.to_s] = value
end
def read_attribute(attribute)
attributes[attribute.to_s]
end
def write_attribute(attribute, value)
attributes[attribute.to_s] = value
end
private
def add_attribute(attribute)
metaclass.class_eval do
attribute = attribute.to_s.gsub /\=$/, ''
define_method(attribute) { attributes[attribute] } unless respond_to? attribute
define_method("#{attribute}=") { |value| attributes[attribute] = value } unless respond_to? "#{attribute}="
end
end
def metaclass
class << self; self; end
end
end
end