Skip to content

Commit c2df9f7

Browse files
committed
Add assigned_attribute_names method to return the names of attributes last passed to assign_form_attributes method
1 parent 18a047c commit c2df9f7

File tree

2 files changed

+32
-0
lines changed

2 files changed

+32
-0
lines changed

lib/hyper_active_form/base.rb

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,10 @@ class Base
1919

2020
define_model_callbacks :assign_form_attributes, :submit
2121

22+
# The list of attribute names that have been passed to the form
23+
# during the last call to `assign_form_attributes` or `submit`
24+
attr_reader :assigned_attribute_names
25+
2226
# Defines to which object the form should delegate the active model methods
2327
# This is useful so `form_for`/`form_with` can automatically deduce the url and method to use
2428
#
@@ -53,6 +57,7 @@ def assign_form_attributes(params)
5357
default_value = self.class._default_attributes[attribute]&.value_before_type_cast
5458
public_send(:"#{attribute}=", params&.dig(attribute) || default_value)
5559
end
60+
@assigned_attribute_names = params.slice(*attribute_names).keys
5661
end
5762
end
5863

spec/hyper_active_form/base_spec.rb

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -118,6 +118,33 @@ def perform
118118
end
119119
end
120120

121+
describe "#assigned_attribute_names" do
122+
context "passing some attributes" do
123+
it "returns the list of attributes" do
124+
form = dummy_class.new(name: "John", age: 20)
125+
form.submit(name: "Fred", age: 19)
126+
expect(form.assigned_attribute_names).to eq(%w[name age])
127+
end
128+
end
129+
130+
context "passing all attributes" do
131+
it "returns the list of attributes" do
132+
form = dummy_class.new(name: "John", age: 20)
133+
form.submit(name: "Fred", age: 19, hobbies: ["reading", "coding"])
134+
expect(form.assigned_attribute_names).to eq(%w[name age hobbies])
135+
end
136+
end
137+
138+
context "multiple calls" do
139+
it "returns the last list of attributes" do
140+
form = dummy_class.new(name: "John", age: 20)
141+
form.submit(name: "Fred", age: 19, hobbies: ["reading", "coding"])
142+
form.submit(name: "John", age: 20)
143+
expect(form.assigned_attribute_names).to eq(%w[name age])
144+
end
145+
end
146+
end
147+
121148
describe ".proxy_for" do
122149
let(:dummy_class) do
123150
Class.new(HyperActiveForm::Base) do

0 commit comments

Comments
 (0)