From 4c8c31774a7c44080099f4a9c7e21d76fa097e09 Mon Sep 17 00:00:00 2001 From: ebyrds Date: Fri, 23 Nov 2018 23:55:31 +0000 Subject: [PATCH] Raises error when attempting to modify enum values --- activerecord/CHANGELOG.md | 4 ++++ activerecord/lib/active_record/enum.rb | 1 + activerecord/test/cases/enum_test.rb | 14 ++++++++++++++ 3 files changed, 19 insertions(+) diff --git a/activerecord/CHANGELOG.md b/activerecord/CHANGELOG.md index 24a64e9deb..95f9cf6d14 100644 --- a/activerecord/CHANGELOG.md +++ b/activerecord/CHANGELOG.md @@ -1,3 +1,7 @@ +* Values of enum are frozen, raising an error when attempting to modify them. + + *Emmanuel Byrd* + * Move `ActiveRecord::StatementInvalid` SQL to error property and include binds as separate error property. `ActiveRecord::ConnectionAdapters::AbstractAdapter#translate_exception_class` now requires `binds` to be passed as the last argument. diff --git a/activerecord/lib/active_record/enum.rb b/activerecord/lib/active_record/enum.rb index 3a600835e1..d62cd3f92a 100644 --- a/activerecord/lib/active_record/enum.rb +++ b/activerecord/lib/active_record/enum.rb @@ -199,6 +199,7 @@ module ActiveRecord klass.scope value_method_name, -> { where(attr => value) } end end + enum_values.freeze end end diff --git a/activerecord/test/cases/enum_test.rb b/activerecord/test/cases/enum_test.rb index 867ce7082b..fef06e6edd 100644 --- a/activerecord/test/cases/enum_test.rb +++ b/activerecord/test/cases/enum_test.rb @@ -438,6 +438,20 @@ class EnumTest < ActiveRecord::TestCase assert_equal ["drafted", "uploaded"], book2.status_change end + test "attempting to modify enum raises error" do + e = assert_raises(RuntimeError) do + Book.statuses["bad_enum"] = 40 + end + + assert_match(/can't modify frozen/, e.message) + + e = assert_raises(RuntimeError) do + Book.statuses.delete("published") + end + + assert_match(/can't modify frozen/, e.message) + end + test "declare multiple enums at a time" do klass = Class.new(ActiveRecord::Base) do self.table_name = "books"