mirror of
https://github.com/rails/rails.git
synced 2022-11-09 12:12:34 -05:00
Merge pull request #18663 from egilburg/reuse-attribute-assignment
Use attribute assignment module logic during ActiveModel initialization.
This commit is contained in:
commit
9bf9097973
3 changed files with 17 additions and 5 deletions
|
@ -1,3 +1,14 @@
|
||||||
|
* Assigning an unknown attribute key to an `ActiveModel` instance during initialization
|
||||||
|
will now raise `ActiveModel::AttributeAssignment::UnknownAttributeError` instead of
|
||||||
|
`NoMethodError`
|
||||||
|
|
||||||
|
```ruby
|
||||||
|
User.new(foo: 'some value')
|
||||||
|
# => ActiveModel::AttributeAssignment::UnknownAttributeError: unknown attribute 'foo' for User.
|
||||||
|
```
|
||||||
|
|
||||||
|
*Eugene Gilburg*
|
||||||
|
|
||||||
* Extracted `ActiveRecord::AttributeAssignment` to `ActiveModel::AttributeAssignment`
|
* Extracted `ActiveRecord::AttributeAssignment` to `ActiveModel::AttributeAssignment`
|
||||||
allowing to use it for any object as an includable module
|
allowing to use it for any object as an includable module
|
||||||
|
|
||||||
|
|
|
@ -57,6 +57,7 @@ module ActiveModel
|
||||||
# (see below).
|
# (see below).
|
||||||
module Model
|
module Model
|
||||||
extend ActiveSupport::Concern
|
extend ActiveSupport::Concern
|
||||||
|
include ActiveModel::AttributeAssignment
|
||||||
include ActiveModel::Validations
|
include ActiveModel::Validations
|
||||||
include ActiveModel::Conversion
|
include ActiveModel::Conversion
|
||||||
|
|
||||||
|
@ -75,10 +76,8 @@ module ActiveModel
|
||||||
# person = Person.new(name: 'bob', age: '18')
|
# person = Person.new(name: 'bob', age: '18')
|
||||||
# person.name # => "bob"
|
# person.name # => "bob"
|
||||||
# person.age # => "18"
|
# person.age # => "18"
|
||||||
def initialize(params={})
|
def initialize(attributes={})
|
||||||
params.each do |attr, value|
|
assign_attributes(attributes) if attributes
|
||||||
self.public_send("#{attr}=", value)
|
|
||||||
end if params
|
|
||||||
|
|
||||||
super()
|
super()
|
||||||
end
|
end
|
||||||
|
|
|
@ -70,6 +70,8 @@ class ModelTest < ActiveModel::TestCase
|
||||||
end
|
end
|
||||||
|
|
||||||
def test_mixin_initializer_when_args_dont_exist
|
def test_mixin_initializer_when_args_dont_exist
|
||||||
assert_raises(NoMethodError) { SimpleModel.new(hello: 'world') }
|
assert_raises(ActiveModel::AttributeAssignment::UnknownAttributeError) do
|
||||||
|
SimpleModel.new(hello: 'world')
|
||||||
|
end
|
||||||
end
|
end
|
||||||
end
|
end
|
||||||
|
|
Loading…
Reference in a new issue