Skip to content

Commit c4c8b43

Browse files
committed
Adds test for embedded shallow attributes with unexpected parameters
1 parent 51f5c1b commit c4c8b43

File tree

2 files changed

+44
-4
lines changed

2 files changed

+44
-4
lines changed

lib/shallow_attributes/type.rb

Lines changed: 21 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,13 @@
77
require 'shallow_attributes/type/time'
88
require 'shallow_attributes/type/date'
99

10+
# Boolean class for working with bool values
11+
#
12+
# @private
13+
#
14+
# @since 0.9.4
15+
class Boolean; end
16+
1017
module ShallowAttributes
1118
# Namespace for standard type classes
1219
#
@@ -30,7 +37,8 @@ class InvalidValueError < TypeError
3037
::Integer => ShallowAttributes::Type::Integer.new,
3138
::String => ShallowAttributes::Type::String.new,
3239
::Time => ShallowAttributes::Type::Time.new,
33-
::Date => ShallowAttributes::Type::Date.new
40+
::Date => ShallowAttributes::Type::Date.new,
41+
::Boolean => ShallowAttributes::Type::Boolean.new
3442
}.freeze
3543

3644
class << self
@@ -56,7 +64,10 @@ class << self
5664
#
5765
# @since 0.1.0
5866
def coerce(type, value, options = {})
59-
type_instance(type).coerce(value, options)
67+
instance = type_instance(type, value)
68+
return instance.coerce(instance.attributes, options) if instance.respond_to? :attributes
69+
70+
instance.coerce(value, options)
6071
end
6172

6273
private
@@ -78,8 +89,14 @@ def coerce(type, value, options = {})
7889
# @return [Class]
7990
#
8091
# @since 0.1.0
81-
def type_instance(klass)
82-
DEFAULT_TYPE_OBJECTS[klass] || ShallowAttributes::Type.const_get(klass.name).new
92+
def type_instance(klass, value = {})
93+
return DEFAULT_TYPE_OBJECTS[klass] if DEFAULT_TYPE_OBJECTS[klass]
94+
95+
instantiable = ShallowAttributes::Type.const_get(klass.name)
96+
97+
return instantiable.new(value) if instantiable < ShallowAttributes
98+
99+
instantiable.new
83100
end
84101
end
85102
end

test/custom_types_test.rb

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -152,5 +152,28 @@ class Person
152152
end
153153
end
154154
end
155+
describe 'when custom type receives parameters not considered as attributes' do
156+
let(:person) do
157+
Person.new(
158+
name: 'John',
159+
address: {
160+
street: 'Street',
161+
number: '12'
162+
}
163+
)
164+
end
165+
166+
it 'ignores the non existence parameter' do
167+
hash = person.attributes
168+
hash.must_equal({
169+
name: 'John',
170+
addresses: [],
171+
address: {
172+
street: 'Street',
173+
zipcode: '111111'
174+
}
175+
})
176+
end
177+
end
155178
end
156179
end

0 commit comments

Comments
 (0)