Skip to content

Commit ae87cca

Browse files
committed
Element can accept values so we can build flat arrays
That is arrays which do not contain hashes
1 parent 16a640b commit ae87cca

File tree

2 files changed

+27
-2
lines changed

2 files changed

+27
-2
lines changed

lib/serial/array_builder.rb

+8-2
Original file line numberDiff line numberDiff line change
@@ -20,8 +20,14 @@ def initialize(context)
2020
#
2121
# @yield [builder]
2222
# @yieldparam builder [HashBuilder]
23-
def element(&block)
24-
@data << HashBuilder.build(@context, &block)
23+
def element(value = :__not_used__, &block)
24+
if value == :__not_used__
25+
@data << HashBuilder.build(@context, &block)
26+
elsif not block
27+
@data << value
28+
else
29+
raise ArgumentError, "cannot pass both a block and an argument to `element`"
30+
end
2531
end
2632

2733
# @api public

spec/serial/dsl_spec.rb

+19
Original file line numberDiff line numberDiff line change
@@ -197,6 +197,25 @@ def collection(&block)
197197
]
198198
})
199199
end
200+
201+
it "accepts a value" do
202+
data = collection do |l|
203+
l.element("hello")
204+
l.element("world")
205+
end
206+
207+
expect(data).to eq({
208+
"collection" => ["hello", "world"]
209+
})
210+
end
211+
212+
it "raises an error when both block and value given" do
213+
expect do
214+
collection do |l|
215+
l.element("hello") { |h| h.attribute(:foo, "bar") }
216+
end
217+
end.to raise_error(ArgumentError, "cannot pass both a block and an argument to `element`")
218+
end
200219
end
201220

202221
describe "#collection" do

0 commit comments

Comments
 (0)