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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
|
# File 'lib/good.rb', line 16
def self.generate(mutable, *members, &block)
Class.new do
mutable ? attr_accessor(*members) : attr_reader(*members)
const_set(:MEMBERS, members.dup.freeze)
def self.coerce(coercable)
case coercable
when self then coercable
when Hash then new(coercable)
else raise TypeError, "Unable to coerce #{coercable.class} into #{self}"
end
end
if mutable
def initialize(attributes = {})
attributes.each { |k, v| send("#{k}=", v) }
end
else
def initialize(attributes = {})
attributes.each { |k, v| instance_variable_set(:"@#{k}", v) }
end
end
def attributes
{}.tap { |h| self.class::MEMBERS.each { |m| h[m] = send(m) } }
end
def members
self.class::MEMBERS.dup
end
def values
self.class::MEMBERS.map { |m| send(m) }
end
def merge(attributes={})
self.class.new(self.attributes.merge(attributes))
end
def ==(other)
other.is_a?(self.class) && attributes == other.attributes
end
def eql?(other)
self == other
end
def hash
attributes.hash
end
class_eval(&block) if block
end
end
|