Class: Yarrow::Schema::Entity
- Inherits:
-
Object
- Object
- Yarrow::Schema::Entity
show all
- Defined in:
- lib/yarrow/schema/entity.rb
Overview
Entity with comparison by reference equality. Generates attribute helpers for a declared set of props. Used to replace Hashie::Mash without dragging in a whole new library.
Class Method Summary
collapse
Instance Method Summary
collapse
Constructor Details
#initialize(config) ⇒ Entity
Returns a new instance of Entity.
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
|
# File 'lib/yarrow/schema/entity.rb', line 31
def initialize(config)
converted = dictionary.cast(config)
converted.each_pair do |key, value|
instance_variable_set("@#{key}", value)
end
end
|
Class Method Details
.[](label) ⇒ Object
17
18
19
20
|
# File 'lib/yarrow/schema/entity.rb', line 17
def [](label)
@label = label
self
end
|
.attribute(name, value_type) ⇒ Object
8
9
10
11
|
# File 'lib/yarrow/schema/entity.rb', line 8
def attribute(name, value_type)
dictionary.define_attribute(name, value_type)
attr_reader(name)
end
|
.dictionary ⇒ Object
13
14
15
|
# File 'lib/yarrow/schema/entity.rb', line 13
def dictionary
@dictionary ||= Dictionary.new({})
end
|
.inherited(class_name) ⇒ Object
22
23
24
25
26
27
28
|
# File 'lib/yarrow/schema/entity.rb', line 22
def inherited(class_name)
if @label
class_type = Yarrow::Schema::Types::Instance.of(class_name)
Yarrow::Schema::Definitions.register(@label, class_type)
@label = nil
end
end
|
Instance Method Details
#merge(other) ⇒ Object
61
62
63
64
65
66
67
|
# File 'lib/yarrow/schema/entity.rb', line 61
def merge(other)
unless other.is_a?(self.class)
raise ArgumentError.new("cannot merge entities that are not the same type")
end
self.class.new(to_h.merge(other.to_h))
end
|
#to_h ⇒ Object
47
48
49
50
51
52
53
54
55
56
57
58
59
|
# File 'lib/yarrow/schema/entity.rb', line 47
def to_h
dictionary.attr_names.reduce({}) do |attr_dict, name|
value = instance_variable_get("@#{name}")
attr_dict[name] = if value.respond_to?(:to_h)
value.to_h
else
value
end
attr_dict
end
end
|