Skip to content

Commit 0acdee1

Browse files
authored
Merge pull request #31 from f-mer/feature/strict-option
Add strict option
2 parents 97673ce + e10c446 commit 0acdee1

File tree

4 files changed

+24
-4
lines changed

4 files changed

+24
-4
lines changed

lib/shallow_attributes/type/date_time.rb

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -24,15 +24,19 @@ class DateTime
2424
# @return [DateTime]
2525
#
2626
# @since 0.1.0
27-
def coerce(value, _options = {})
27+
def coerce(value, options = {})
2828
case value
2929
when ::DateTime then value
3030
when ::Time then ::DateTime.parse(value.to_s)
3131
else
3232
::DateTime.parse(value)
3333
end
3434
rescue
35-
raise ShallowAttributes::Type::InvalidValueError, %(Invalid value "#{value}" for type "DateTime")
35+
if options.fetch(:strict, true)
36+
raise ShallowAttributes::Type::InvalidValueError, %(Invalid value "#{value}" for type "DateTime")
37+
else
38+
nil
39+
end
3640
end
3741
end
3842
end

lib/shallow_attributes/type/time.rb

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -22,15 +22,19 @@ class Time
2222
# @return [Time]
2323
#
2424
# @since 0.1.0
25-
def coerce(value, _options = {})
25+
def coerce(value, options = {})
2626
case value
2727
when ::Time then value
2828
when ::Integer then ::Time.at(value)
2929
else
3030
::Time.parse(value.to_s)
3131
end
3232
rescue
33-
raise ShallowAttributes::Type::InvalidValueError, %(Invalid value "#{value}" for type "Time")
33+
if options.fetch(:strict, true)
34+
raise ShallowAttributes::Type::InvalidValueError, %(Invalid value "#{value}" for type "Time")
35+
else
36+
nil
37+
end
3438
end
3539
end
3640
end

test/date_time_type_test.rb

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -48,6 +48,12 @@
4848
end
4949
end
5050

51+
describe 'when strict is false' do
52+
it 'returns nil' do
53+
assert_nil type.coerce(nil, strict: false)
54+
end
55+
end
56+
5157
describe 'when value is TrueClass' do
5258
it 'returns InvalidValueError' do
5359
err = -> { type.coerce(true) }.must_raise ShallowAttributes::Type::InvalidValueError

test/time_type_test.rb

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -50,6 +50,12 @@
5050
end
5151
end
5252

53+
describe 'when strict is false' do
54+
it 'returns nil' do
55+
assert_nil type.coerce(nil, strict: false)
56+
end
57+
end
58+
5359
describe 'when value is TrueClass' do
5460
it 'returns InvalidValueError' do
5561
err = -> { type.coerce(true) }.must_raise ShallowAttributes::Type::InvalidValueError

0 commit comments

Comments
 (0)