Skip to content

Commit f12cf14

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

File tree

2 files changed

+76
-4
lines changed

2 files changed

+76
-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

+74-2
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,10 @@
11
describe "invalid default value assignment" do
2+
shared_examples "it has a TypeError" do
3+
it "raises TypeError" do
4+
expect { subject }.to raise_error TypeError
5+
end
6+
end
7+
28
subject do
39
class Test::Foo
410
extend Dry::Initializer
@@ -7,7 +13,73 @@ class Test::Foo
713
end
814
end
915

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

0 commit comments

Comments
 (0)