Skip to content

Commit

Permalink
Don't coerce nil for collection attributes when required is false
Browse files Browse the repository at this point in the history
Without this fix, collection attributes can never be set to nil when
coercion is enabled (because the coercer coerces nil to an empty array).
  • Loading branch information
mherold committed Mar 1, 2016
1 parent c4c0412 commit f391d1f
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 5 deletions.
2 changes: 1 addition & 1 deletion lib/virtus/attribute/collection.rb
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,7 @@ def self.merge_options!(type, options)

# @api public
def coerce(value)
coerced = super
coerced = value.nil? && !required? ? nil : super

return coerced unless coerced.respond_to?(:each_with_object)

Expand Down
21 changes: 17 additions & 4 deletions spec/unit/virtus/attribute/collection/coerce_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -61,14 +61,27 @@

let(:object) {
described_class.build(
Array[member_primitive], coercer: coercer, member_type: member_type
Array[member_primitive], coercer: coercer, member_type: member_type, required: required
)
}

it 'returns nil' do
mock(coercer).call(input) { input }
context 'when required' do
let(:required) { true }
let(:output) { Array(input) }

expect(subject).to be(input)
it 'returns an empty array' do
mock(coercer).call(input) { output }

expect(subject).to eq(output)
end
end

context 'when not required' do
let(:required) { false }

it 'returns nil' do
expect(subject).to be(input)
end
end
end
end

0 comments on commit f391d1f

Please sign in to comment.