diff options
author | Yves Senn <yves.senn@gmail.com> | 2013-11-04 19:54:46 +0100 |
---|---|---|
committer | Yves Senn <yves.senn@gmail.com> | 2013-11-05 17:44:08 +0100 |
commit | 6c720d18a2770299433fae82c1cab25d0bd4033e (patch) | |
tree | 9e9939ef8bd1aab35d3b5ac775d9802200e24d60 | |
parent | 81a528fc0caff94e837249e51bf96d65c4967c7b (diff) | |
download | rails-6c720d18a2770299433fae82c1cab25d0bd4033e.tar.gz rails-6c720d18a2770299433fae82c1cab25d0bd4033e.tar.bz2 rails-6c720d18a2770299433fae82c1cab25d0bd4033e.zip |
direct enum assignment rasies ArgumentError for unknown values.
-rw-r--r-- | activerecord/lib/active_record/enum.rb | 7 | ||||
-rw-r--r-- | activerecord/test/cases/enum_test.rb | 12 |
2 files changed, 18 insertions, 1 deletions
diff --git a/activerecord/lib/active_record/enum.rb b/activerecord/lib/active_record/enum.rb index efea9560ee..6bfdf75a2d 100644 --- a/activerecord/lib/active_record/enum.rb +++ b/activerecord/lib/active_record/enum.rb @@ -42,7 +42,12 @@ module ActiveRecord _enum_methods_module.module_eval do # def direction=(value) self[:direction] = DIRECTION[value] end - define_method("#{name}=") { |value| self[name] = enum_values[value] } + define_method("#{name}=") { |value| + unless enum_values.has_key?(value) + raise ArgumentError, "'#{value}' is not a valid #{name}" + end + self[name] = enum_values[value] + } # def direction() DIRECTION.key self[:direction] end define_method(name) { enum_values.key self[name] } diff --git a/activerecord/test/cases/enum_test.rb b/activerecord/test/cases/enum_test.rb index bb9faccf1b..087db4c32c 100644 --- a/activerecord/test/cases/enum_test.rb +++ b/activerecord/test/cases/enum_test.rb @@ -40,4 +40,16 @@ class EnumTest < ActiveRecord::TestCase assert_equal "do publish work...", @book.published! assert @book.published? end + + test "direct assignment" do + @book.status = :written + assert @book.written? + end + + test "assign non existing value raises an error" do + e = assert_raises(ArgumentError) do + @book.status = :unknown + end + assert_equal "'unknown' is not a valid status", e.message + end end |