Class: Rasti::DB::Model
- Inherits:
-
Object
show all
- Defined in:
- lib/rasti/db/model.rb
Defined Under Namespace
Classes: UninitializedAttributeError
Class Method Summary
collapse
Instance Method Summary
collapse
Constructor Details
#initialize(attributes) ⇒ Model
Returns a new instance of Model.
59
60
61
62
63
|
# File 'lib/rasti/db/model.rb', line 59
def initialize(attributes)
invalid_attributes = attributes.keys - self.class.attributes
raise "#{self.class.model_name} invalid attributes: #{invalid_attributes.join(', ')}" unless invalid_attributes.empty?
@attributes = attributes
end
|
Class Method Details
.[](*attribute_names) ⇒ Object
19
20
21
22
23
24
25
26
27
|
# File 'lib/rasti/db/model.rb', line 19
def [](*attribute_names)
Class.new(self) do
attribute(*attribute_names)
def self.inherited(subclass)
subclass.instance_variable_set :@attributes, attributes.dup
end
end
end
|
.attributes ⇒ Object
29
30
31
|
# File 'lib/rasti/db/model.rb', line 29
def attributes
@attributes ||= []
end
|
.inspect ⇒ Object
40
41
42
|
# File 'lib/rasti/db/model.rb', line 40
def to_s
"#{model_name}[#{attributes.join(', ')}]"
end
|
.model_name ⇒ Object
33
34
35
|
# File 'lib/rasti/db/model.rb', line 33
def model_name
name || self.superclass.name
end
|
.to_s ⇒ Object
37
38
39
|
# File 'lib/rasti/db/model.rb', line 37
def to_s
"#{model_name}[#{attributes.join(', ')}]"
end
|
Instance Method Details
#==(other) ⇒ Object
73
74
75
|
# File 'lib/rasti/db/model.rb', line 73
def ==(other)
other.kind_of?(self.class) && to_h == other.to_h
end
|
#eql?(other) ⇒ Boolean
69
70
71
|
# File 'lib/rasti/db/model.rb', line 69
def eql?(other)
instance_of?(other.class) && to_h.eql?(other.to_h)
end
|
#hash ⇒ Object
77
78
79
|
# File 'lib/rasti/db/model.rb', line 77
def hash
attributes.map(&:hash).hash
end
|
#merge(new_attributes) ⇒ Object
65
66
67
|
# File 'lib/rasti/db/model.rb', line 65
def merge(new_attributes)
self.class.new attributes.merge(new_attributes)
end
|
#to_h ⇒ Object
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
|
# File 'lib/rasti/db/model.rb', line 86
def to_h
self.class.attributes.each_with_object({}) do |name, hash|
if attributes.key? name
value = fetch_attribute name
case value
when Model
hash[name] = value.to_h
when Array
hash[name] = value.map do |e|
e.is_a?(Model) ? e.to_h : e
end
else
hash[name] = value
end
end
end
end
|
#to_s ⇒ Object
Also known as:
inspect
81
82
83
|
# File 'lib/rasti/db/model.rb', line 81
def to_s
"#<#{self.class.model_name}[#{attributes.map { |n,v| "#{n}: #{v.inspect}" }.join(', ')}]>"
end
|