Skip to content

Commit 2244311

Browse files
committed
Mix ActiveModel::AttributeAssignment into Base
By including the [ActiveModel::AttributeAssignment][], the `Base` class can access the [assign_attributes][] method for bulk assignment of attributes **without** saving them to the server (like through `Base#update_attributes`). ```ruby Person.schema = { name: "string" } person = Person.new person.id # => nil person.name # => nil person.assign_attributes id: 1, name: "Matz" person.id # => 1 person.name # => "Matz" ``` [ActiveModel::AttributeAssignment]: https://edgeapi.rubyonrails.org/classes/ActiveModel/AttributeAssignment.html [assign_attributes]: https://edgeapi.rubyonrails.org/classes/ActiveModel/AttributeAssignment.html#method-i-assign_attributes
1 parent ea22c4a commit 2244311

File tree

2 files changed

+23
-1
lines changed

2 files changed

+23
-1
lines changed

lib/active_resource/base.rb

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1857,7 +1857,7 @@ class Base
18571857
extend ActiveResource::Associations
18581858

18591859
include Callbacks, CustomMethods, Validations, Serialization
1860-
include ActiveModel::Conversion
1860+
include ActiveModel::AttributeAssignment, ActiveModel::Conversion
18611861
include ActiveModel::ForbiddenAttributesProtection
18621862
include ActiveModel::Serializers::JSON
18631863
include ActiveModel::Serializers::Xml

test/cases/base_test.rb

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1008,6 +1008,28 @@ def test_predicate_for_an_unknown_attribute_returns_nil
10081008
assert_not_predicate post, :unknown_attribute?
10091009
end
10101010

1011+
def test_assign_attributes_to_known_attributes
1012+
previous_schema = Person.schema
1013+
Person.schema = { name: "string" }
1014+
1015+
matz = Person.new
1016+
1017+
matz.assign_attributes "id" => 1, :name => "Matz"
1018+
1019+
assert_equal 1, matz.id
1020+
assert_equal "Matz", matz.name
1021+
ensure
1022+
Person.schema = previous_schema
1023+
end
1024+
1025+
def test_assign_attributes_assigns_to_loaded_attributes
1026+
matz = Person.new(name: "matz")
1027+
1028+
assert_changes -> { matz.name }, from: "matz", to: "Matz" do
1029+
matz.assign_attributes(name: "Matz")
1030+
end
1031+
end
1032+
10111033
def test_custom_header
10121034
Person.headers["key"] = "value"
10131035
assert_raise(ActiveResource::ResourceNotFound) { Person.find(4) }

0 commit comments

Comments
 (0)