Skip to content

Commit

Permalink
Fix arity check for defaults
Browse files Browse the repository at this point in the history
  • Loading branch information
skryukov committed Oct 11, 2021
1 parent 63b07c9 commit 1e6e9f2
Show file tree
Hide file tree
Showing 2 changed files with 78 additions and 4 deletions.
4 changes: 2 additions & 2 deletions lib/dry/initializer/dispatchers/prepare_default.rb
Original file line number Diff line number Diff line change
Expand Up @@ -26,8 +26,8 @@ def callable!(default)
def check_arity!(default)
return unless default

arity = default.method(:call).arity.to_i
return unless arity.positive?
arity = default.is_a?(Proc) ? default.arity : default.method(:call).arity
return if arity.equal?(0) || arity.equal?(-1)

invalid!(default)
end
Expand Down
78 changes: 76 additions & 2 deletions spec/invalid_default_spec.rb
Original file line number Diff line number Diff line change
@@ -1,4 +1,12 @@
# frozen_string_literal: true

describe "invalid default value assignment" do
shared_examples "it has a TypeError" do
it "raises TypeError" do
expect { subject }.to raise_error TypeError
end
end

subject do
class Test::Foo
extend Dry::Initializer
Expand All @@ -7,7 +15,73 @@ class Test::Foo
end
end

it "raises TypeError" do
expect { subject }.to raise_error TypeError
it_behaves_like "it has a TypeError"

context "when default is a lambda one attribute with splat operator" do
subject do
class Test::Foo
extend Dry::Initializer

param :foo, default: ->(a) { a.to_i }
end
end

it_behaves_like "it has a TypeError"
end

context "when default is a proc with attributes" do
subject do
class Test::Foo
extend Dry::Initializer

param :foo, default: proc { |a| a.to_i }
end
end

it_behaves_like "it has a TypeError"
end

context "when default is a callable with attributes" do
subject do
class Test::Callbale
def self.call(a)
a.to_i
end
end

class Test::Foo
extend Dry::Initializer

param :foo, default: Test::Callbale
end
end

it_behaves_like "it has a TypeError"
end

context "when default is a proc with multiple attributes" do
subject do
class Test::Foo
extend Dry::Initializer

param :foo, default: proc { |a, *b| a.to_i }
end
end

it_behaves_like "it has a TypeError"
end

context "when default is a lambda one attribute with splat operator" do
subject do
class Test::Foo
extend Dry::Initializer

param :foo, default: ->(*a) { a.size }
end
end

it "does not raise TypeError" do
expect { subject }.not_to raise_error
end
end
end

0 comments on commit 1e6e9f2

Please sign in to comment.