Skip to content

Commit 1e6e9f2

Browse files
committed
Fix arity check for defaults
1 parent 63b07c9 commit 1e6e9f2

File tree

2 files changed

+78
-4
lines changed

2 files changed

+78
-4
lines changed

lib/dry/initializer/dispatchers/prepare_default.rb

+2-2
Original file line numberDiff line numberDiff line change
@@ -26,8 +26,8 @@ def callable!(default)
2626
def check_arity!(default)
2727
return unless default
2828

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

3232
invalid!(default)
3333
end

spec/invalid_default_spec.rb

+76-2
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,12 @@
1+
# frozen_string_literal: true
2+
13
describe "invalid default value assignment" do
4+
shared_examples "it has a TypeError" do
5+
it "raises TypeError" do
6+
expect { subject }.to raise_error TypeError
7+
end
8+
end
9+
210
subject do
311
class Test::Foo
412
extend Dry::Initializer
@@ -7,7 +15,73 @@ class Test::Foo
715
end
816
end
917

10-
it "raises TypeError" do
11-
expect { subject }.to raise_error TypeError
18+
it_behaves_like "it has a TypeError"
19+
20+
context "when default is a lambda one attribute with splat operator" do
21+
subject do
22+
class Test::Foo
23+
extend Dry::Initializer
24+
25+
param :foo, default: ->(a) { a.to_i }
26+
end
27+
end
28+
29+
it_behaves_like "it has a TypeError"
30+
end
31+
32+
context "when default is a proc with attributes" do
33+
subject do
34+
class Test::Foo
35+
extend Dry::Initializer
36+
37+
param :foo, default: proc { |a| a.to_i }
38+
end
39+
end
40+
41+
it_behaves_like "it has a TypeError"
42+
end
43+
44+
context "when default is a callable with attributes" do
45+
subject do
46+
class Test::Callbale
47+
def self.call(a)
48+
a.to_i
49+
end
50+
end
51+
52+
class Test::Foo
53+
extend Dry::Initializer
54+
55+
param :foo, default: Test::Callbale
56+
end
57+
end
58+
59+
it_behaves_like "it has a TypeError"
60+
end
61+
62+
context "when default is a proc with multiple attributes" do
63+
subject do
64+
class Test::Foo
65+
extend Dry::Initializer
66+
67+
param :foo, default: proc { |a, *b| a.to_i }
68+
end
69+
end
70+
71+
it_behaves_like "it has a TypeError"
72+
end
73+
74+
context "when default is a lambda one attribute with splat operator" do
75+
subject do
76+
class Test::Foo
77+
extend Dry::Initializer
78+
79+
param :foo, default: ->(*a) { a.size }
80+
end
81+
end
82+
83+
it "does not raise TypeError" do
84+
expect { subject }.not_to raise_error
85+
end
1286
end
1387
end

0 commit comments

Comments
 (0)