Is there any way to "turn on" the strict arity enforcement of a Proc instantiated using Proc.new
or Kernel.proc
, so that it behaves like a Proc instantiated with lambda
?
My initialize
method takes a block &action
and assigns it to an instance variable. I want action
to strictly enforce arity, so when I apply arguments to it later on, it raises an ArgumentError
that I can rescue and raise a more meaningful exception. Basically:
class Command
attr_reader :name, :action
def initialize(name, &action)
@name = name
@action = action
end
def perform(*args)
begin
action.call(*args)
rescue ArgumentError
raise(WrongArity.new(args.size))
end
end
end
class WrongArity < StandardError; end
Unfortunately, action
does not enforce arity by default:
c = Command.new('second_argument') { |_, y| y }
c.perform(1) # => nil
action.to_proc
doesn't work, nor does lambda(&action)
.
Any other ideas? Or better approaches to the problem?
Thanks!