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, context = nil) ⇒ Entity
Returns a new instance of Entity.
36
37
38
39
40
41
42
43
|
# File 'lib/yarrow/schema/entity.rb', line 36
def initialize(config, context=nil)
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
Instance Method Details
#merge(other) ⇒ Object
67
68
69
70
71
72
73
|
# File 'lib/yarrow/schema/entity.rb', line 67
def merge(other)
unless other.is_a?(self.class) || other.is_a?(Hash)
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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
|
# File 'lib/yarrow/schema/entity.rb', line 45
def to_h
dictionary.attr_names.reduce({}) do |attr_dict, name|
value = instance_variable_get("@#{name}")
attr_dict[name] =if value.is_a?(Array)
value.map do |entry|
if entry.respond_to?(:to_h)
entry.to_h
else
entry
end
end
elsif value.respond_to?(:to_h)
value.to_h
else
value
end
attr_dict
end
end
|