Skip to content

Commit 36b8e3f

Browse files
committed
Fix behaviour when params are falsey, making their value nil instead of the original falsey value
1 parent ffc6a1d commit 36b8e3f

File tree

2 files changed

+16
-3
lines changed

2 files changed

+16
-3
lines changed

lib/hyper_active_form/base.rb

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -55,7 +55,11 @@ def assign_form_attributes(params)
5555
params = ActionController::Parameters.new(params) unless params.is_a?(ActionController::Parameters)
5656
attribute_names.each do |attribute|
5757
default_value = self.class._default_attributes[attribute]&.value_before_type_cast
58-
public_send(:"#{attribute}=", params&.dig(attribute) || default_value)
58+
if params&.key?(attribute)
59+
public_send(:"#{attribute}=", params&.dig(attribute))
60+
else
61+
public_send(:"#{attribute}=", default_value)
62+
end
5963
end
6064
@assigned_attribute_names = params.slice(*attribute_names).keys
6165
end

spec/hyper_active_form/base_spec.rb

Lines changed: 11 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@ def self.model_name
1313
attribute :name
1414
attribute :age
1515
attribute :hobbies, default: []
16+
attribute :likes_cats, :boolean
1617

1718
def self.model_name
1819
ActiveModel::Name.new(self, nil, "Dummy")
@@ -29,7 +30,7 @@ def setup(name:, age:, perform_return_value: true, callable: nil)
2930
end
3031

3132
def perform
32-
@callable&.call
33+
@callable&.call(attributes)
3334
@perform_return_value
3435
end
3536
end
@@ -63,7 +64,7 @@ def perform
6364
context "when the form is valid" do
6465
it "returns true and performs the form" do
6566
form = dummy_class.new(name: "John", age: 20, callable:)
66-
expect(callable).to receive(:call)
67+
expect(callable).to receive(:call).with({"name" => "Fred", "age" => 19, "hobbies" => [], "likes_cats" => nil})
6768
expect(form.submit(name: "Fred", age: 19)).to eq(true)
6869
end
6970

@@ -73,6 +74,14 @@ def perform
7374
form.submit(name: "Fred", age: 19)
7475
end
7576

77+
context "with falsey parameters" do
78+
it "assigns the attributes correctly" do
79+
form = dummy_class.new(name: "John", age: 20, callable:)
80+
expect(callable).to receive(:call).with({"name" => "Fred", "age" => 19, "hobbies" => [], "likes_cats" => false})
81+
form.submit(name: "Fred", age: 19, likes_cats: false)
82+
end
83+
end
84+
7685
end
7786

7887
context "when the form is invalid" do

0 commit comments

Comments
 (0)