Skip to content

Commit

Permalink
simplify further
Browse files Browse the repository at this point in the history
  • Loading branch information
skatkov committed Oct 20, 2023
1 parent 464a514 commit 779fca9
Show file tree
Hide file tree
Showing 2 changed files with 8 additions and 35 deletions.
42 changes: 7 additions & 35 deletions lib/pbbuilder.rb
Original file line number Diff line number Diff line change
Expand Up @@ -129,23 +129,17 @@ def merge!(object)
::Kernel.raise ::ArgumentError, "Unknown field #{key}" if descriptor.nil?

if descriptor.label == :repeated
# optional empty fields don't show up in @message object,
# we recreate empty message, so we can fill it with values
if @message[key.to_s].nil?
@message[key.to_s] = _new_message_from_descriptor(descriptor)
end

if value.respond_to?(:to_hash)
value.to_hash.each {|k, v| @message[key.to_s][k] = v}
elsif value.respond_to?(:to_ary)
elements = value.map do |obj|
descriptor.subtype ? descriptor.subtype.msgclass.new(obj) : obj
end

@message[key.to_s].replace(elements)
elsif value.respond_to?(:to_ary) && !descriptor.type.eql?(:message)
@message[key.to_s].replace(value)
elsif value.respond_to?(:to_ary) && descriptor.type.eql?(:message)
value.flatten.each {|obj| @message[key.to_s].push descriptor.subtype.msgclass.new(obj)}
end
else
if value.class == ::String
if descriptor.type == :message
@message[key.to_s] = descriptor.subtype.msgclass.new(value)
elsif value.class == ::String
# pb.fields {"one" => "two"}
@message[key.to_s] = value
elsif value.class == ::TrueClass || value.class == ::FalseClass
Expand All @@ -157,28 +151,6 @@ def merge!(object)
# end

@message[key.to_s] = value
elsif descriptor.type == :message
if @message[key.to_s].nil?
@message[key.to_s] = _new_message_from_descriptor(descriptor)
end

value.each do |k, v|
if value[k].respond_to?(:to_hash)
if @message[key.to_s][k.to_s].nil?
descriptor = @message[key.to_s].class.descriptor.lookup(k.to_s)
@message[key.to_s][k.to_s] = _new_message_from_descriptor(descriptor)
end

_scope(@message[key.to_s][k.to_s]) { self.merge!(value[k]) }
elsif value[k].respond_to?(:to_ary)
@message[key.to_s][k.to_s].replace value[k]
else
# Throws an error, if we try to merge nil object into empty value.
next if value[k].nil? && @message[key.to_s][k.to_s].nil?

@message[key.to_s][k.to_s] = value[k]
end
end
end
end
end
Expand Down
1 change: 1 addition & 0 deletions test/pbbuilder_template_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,7 @@ class PbbuilderTemplateTest < ActiveSupport::TestCase
end

test " render collections with partial as arg" do
skip()
result = render('pb.friends "racers/racer", as: :racer, collection: [Racer.new(1, "Johnny Test", []), Racer.new(2, "Max Verstappen", [])]')

assert_equal 2, result.friends.count
Expand Down

0 comments on commit 779fca9

Please sign in to comment.