Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix arity check for defaults #93

Open
wants to merge 2 commits into
base: fix/default-arity-checks
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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 @@ -30,8 +30,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
76 changes: 74 additions & 2 deletions spec/invalid_default_spec.rb
Original file line number Diff line number Diff line change
@@ -1,6 +1,12 @@
# frozen_string_literal: true

RSpec.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 @@ -9,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