Skip to content

Improve assignment to array #272

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 7 additions & 6 deletions lib/protobuf/field/base_field.rb
Original file line number Diff line number Diff line change
Expand Up @@ -194,6 +194,11 @@ def define_array_setter

message_class.class_eval do
define_method(method_name) do |val|
if val.nil? || (val.respond_to?(:empty?) && val.empty?)
@values.delete(field.name)
return
end

if val.is_a?(Array)
val = val.dup
val.compact!
Expand All @@ -204,12 +209,8 @@ def define_array_setter
TYPE_ERROR
end

if val.nil? || (val.respond_to?(:empty?) && val.empty?)
@values.delete(field.name)
else
@values[field.name] ||= ::Protobuf::Field::FieldArray.new(field)
@values[field.name].replace(val)
end
@values[field.name] ||= ::Protobuf::Field::FieldArray.new(field)
@values[field.name].replace(val)
end
end

Expand Down
2 changes: 1 addition & 1 deletion lib/protobuf/field/field_array.rb
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,7 @@ def normalize(value)
elsif field.is_a?(::Protobuf::Field::MessageField) && value.respond_to?(:to_hash)
field.type_class.new(value.to_hash)
else
value
field.coerce!(value)
end
end

Expand Down
19 changes: 19 additions & 0 deletions spec/lib/protobuf/field/field_array_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ class SomeRepeatMessage < ::Protobuf::Message
optional :string, :some_string, 1
repeated :string, :multiple_strings, 2
repeated SomeBasicMessage, :multiple_basic_msgs, 3
repeated :int64, :multiple_integers, 4
end

let(:instance) { SomeRepeatMessage.new }
Expand Down Expand Up @@ -64,6 +65,24 @@ class SomeRepeatMessage < ::Protobuf::Message
expect(instance.multiple_basic_msgs.first).to be_a(MoreComplexMessage)
end
end

context 'when applied to an Integer field array' do
it 'does conversion if adding a string' do
expect(instance.multiple_integers).to be_empty
instance.multiple_integers.send(method, '1')
expect(instance.multiple_integers).to eq([1])
end
end
end

describe 'assign' do
context 'nil to an array' do
it 'empties the array' do
instance.multiple_strings = ['string 1']
instance.multiple_strings = nil
expect(instance.multiple_strings).to be_empty
end
end
end
end
end