1
0
Fork 0
mirror of https://github.com/rails/rails.git synced 2022-11-09 12:12:34 -05:00

Raise FrozenError for frozen objects when trying to write to a

non-database-backed attribute.

Writing to database-backed attributes after freezing an object would
raise FrozenError, but wouldn't raise FrozenError for user-defined
attributes.

Fixes #37208
This commit is contained in:
Josh Brody 2019-09-16 16:57:47 -05:00
parent a1b6c1669f
commit 54b1574421
3 changed files with 19 additions and 0 deletions

View file

@ -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!")

View file

@ -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

View file

@ -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