Skip to content

Commit

Permalink
Browse files Browse the repository at this point in the history
use attribute assignment module logic during active model initialization
  • Loading branch information
egilburg committed Jan 23, 2015
1 parent 8c83bd0 commit 5bdb421
Show file tree
Hide file tree
Showing 3 changed files with 17 additions and 5 deletions.
11 changes: 11 additions & 0 deletions activemodel/CHANGELOG.md
@@ -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`
allowing to use it for any object as an includable module

Expand Down
7 changes: 3 additions & 4 deletions activemodel/lib/active_model/model.rb
Expand Up @@ -57,6 +57,7 @@ module ActiveModel
# (see below).
module Model
extend ActiveSupport::Concern
include ActiveModel::AttributeAssignment
include ActiveModel::Validations
include ActiveModel::Conversion

Expand All @@ -75,10 +76,8 @@ module Model
# person = Person.new(name: 'bob', age: '18')
# person.name # => "bob"
# person.age # => "18"
def initialize(params={})
params.each do |attr, value|
self.public_send("#{attr}=", value)
end if params
def initialize(attributes={})
assign_attributes(attributes) if attributes

super()
end
Expand Down
4 changes: 3 additions & 1 deletion activemodel/test/cases/model_test.rb
Expand Up @@ -70,6 +70,8 @@ def test_mixin_initializer_when_args_exist
end

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

0 comments on commit 5bdb421

Please sign in to comment.