Skip to content

Commit c163899

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 bdb7f20 commit c163899

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
@@ -1850,7 +1850,7 @@ class Base
18501850
extend ActiveResource::Associations
18511851

18521852
include Callbacks, CustomMethods, Validations, Serialization
1853-
include ActiveModel::Conversion
1853+
include ActiveModel::Conversion, ActiveModel::AttributeAssignment
18541854
include ActiveModel::ForbiddenAttributesProtection
18551855
include ActiveModel::Serializers::JSON
18561856
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)