Skip to content

Commit 12bc859

Browse files
1075461847LiuChun
andauthored
Fix transform with default value (#93)
Fixes #92 --------- Co-authored-by: LiuChun <liuchun@gfttek.com>
1 parent 7dbcfd3 commit 12bc859

File tree

2 files changed

+20
-1
lines changed

2 files changed

+20
-1
lines changed

lib/rails_param/param_evaluator.rb

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -36,7 +36,7 @@ def param!(name, type, options = {}, &block)
3636
recurse_on_parameter(parameter, &block) if block_given?
3737

3838
# apply transformation
39-
parameter.transform if params.include?(name) && options[:transform]
39+
parameter.transform if options[:transform]
4040

4141
# validate
4242
validate!(parameter)

spec/rails_param/param_spec.rb

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,12 @@ def params;
3232
controller.param! :word, String, transform: :upcase
3333
expect(controller.params["word"]).to eql("FOO")
3434
end
35+
36+
it "transforms default value" do
37+
allow(controller).to receive(:params).and_return({})
38+
controller.param! :word, String, default: "foo", transform: :upcase
39+
expect(controller.params["word"]).to eql("FOO")
40+
end
3541
end
3642

3743
context "with a block" do
@@ -41,6 +47,12 @@ def params;
4147
expect(controller.params["word"]).to eql("foo")
4248
end
4349

50+
it "transforms default value" do
51+
allow(controller).to receive(:params).and_return({})
52+
controller.param! :word, String, default: "foo", transform: lambda { |n| n.upcase }
53+
expect(controller.params["word"]).to eql("FOO")
54+
end
55+
4456
it "transforms falsey value" do
4557
allow(controller).to receive(:params).and_return({ "foo" => "0" })
4658
controller.param! :foo, :boolean, transform: lambda { |n| n ? "bar" : "no bar" }
@@ -54,6 +66,13 @@ def params;
5466
expect { controller.param! :foo, String, required: true, transform: :upcase }.to raise_error(RailsParam::InvalidParameterError, "Parameter foo is required")
5567
end
5668
end
69+
70+
context "when param is optional & not present" do
71+
it "doesn't transform the value" do
72+
allow(controller).to receive(:params).and_return({ })
73+
expect { controller.param! :foo, String, transform: :upcase }.not_to raise_error
74+
end
75+
end
5776
end
5877

5978
describe "default" do

0 commit comments

Comments
 (0)