Skip to content

Commit 80cb2f9

Browse files
committed
Clean up ensure_block_arity! dead returns and fix splat-arg edge case
Use block.arity == 1 instead of block.parameters.one? so that splat-arg lambdas (->(*args) { }) receive both object and options instead of being misrouted to the single-arg path. Remove dead return values from ensure_block_arity! since the caller no longer uses its return value — it is now purely a validation method.
1 parent cc14f92 commit 80cb2f9

2 files changed

Lines changed: 15 additions & 3 deletions

File tree

lib/grape_entity/entity.rb

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -528,7 +528,7 @@ def exec_with_object(options, &block)
528528
if symbol_to_proc_wrapper?(block)
529529
ensure_block_arity!(block)
530530
instance_exec(object, &block)
531-
elsif block.parameters.one?
531+
elsif block.arity == 1
532532
instance_exec(object, &block)
533533
else
534534
instance_exec(object, options, &block)
@@ -539,7 +539,7 @@ def ensure_block_arity!(block)
539539
# MRI currently always includes "( &:foo )" for symbol-to-proc wrappers.
540540
# If this format changes in a new Ruby version, this logic must be updated.
541541
origin_method_name = block.to_s.scan(/(?<=\(&:)[^)]+(?=\))/).first&.to_sym
542-
return 0 unless origin_method_name
542+
return unless origin_method_name
543543

544544
unless object.respond_to?(origin_method_name, true)
545545
raise ArgumentError, <<~MSG
@@ -548,7 +548,7 @@ def ensure_block_arity!(block)
548548
end
549549

550550
arity = object.method(origin_method_name).arity
551-
return 0 if arity.zero?
551+
return if arity.zero?
552552

553553
raise ArgumentError, <<~MSG
554554
Cannot use `&:#{origin_method_name}` because that method expects #{arity} argument#{'s' if arity != 1}.

spec/grape_entity/entity_spec.rb

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -500,6 +500,18 @@ def raises_argument_error
500500
expect(value).to eq('result')
501501
end
502502
end
503+
504+
context 'with splat-argument lambda' do
505+
it 'passes the object and options' do
506+
subject.expose :args_count do |*args|
507+
args.size
508+
end
509+
510+
object = SomeObject.new
511+
value = subject.represent(object).value_for(:args_count)
512+
expect(value).to eq(2)
513+
end
514+
end
503515
end
504516

505517
context 'with no parameters passed to the block' do

0 commit comments

Comments
 (0)