mirror of
https://github.com/rails/rails.git
synced 2022-11-09 12:12:34 -05:00
Merge pull request #37217 from joshmn/frozen_attributes
Raise FrozenError for frozen objects when trying to write to a non-database-backed attribute
This commit is contained in:
commit
4c5da6093d
3 changed files with 19 additions and 0 deletions
|
@ -1,3 +1,14 @@
|
|||
* Raise FrozenError when trying to write attributes that aren't backed by the database on an object that is frozen:
|
||||
|
||||
class Animal
|
||||
include ActiveModel::Attributes
|
||||
attribute :age
|
||||
end
|
||||
|
||||
animal = Animal.new
|
||||
animal.freeze
|
||||
animal.age = 25 # => FrozenError, "can't modify a frozen Animal"
|
||||
|
||||
* Add *_previously_was attribute methods when dirty tracking. Example:
|
||||
|
||||
pirate.update(catchphrase: "Ahoy!")
|
||||
|
|
|
@ -48,6 +48,7 @@ module ActiveModel
|
|||
) do |temp_method_name, attr_name_expr|
|
||||
generated_attribute_methods.module_eval <<-RUBY, __FILE__, __LINE__ + 1
|
||||
def #{temp_method_name}(value)
|
||||
raise FrozenError, "can't modify frozen #{self.class.name}" if frozen?
|
||||
name = #{attr_name_expr}
|
||||
write_attribute(name, value)
|
||||
end
|
||||
|
|
|
@ -107,5 +107,12 @@ module ActiveModel
|
|||
|
||||
assert_equal attributes, new_attributes
|
||||
end
|
||||
|
||||
test "can't modify attributes if frozen" do
|
||||
data = ModelForAttributesTest.new
|
||||
data.freeze
|
||||
assert data.frozen?
|
||||
assert_raise(FrozenError) { data.integer_field = 1 }
|
||||
end
|
||||
end
|
||||
end
|
||||
|
|
Loading…
Reference in a new issue