Permalink
Browse files

direct enum assignment rasies ArgumentError for unknown values.

  • Loading branch information...
1 parent 81a528f commit 6c720d18a2770299433fae82c1cab25d0bd4033e @senny senny committed Nov 4, 2013
Showing with 18 additions and 1 deletion.
  1. +6 −1 activerecord/lib/active_record/enum.rb
  2. +12 −0 activerecord/test/cases/enum_test.rb
@@ -42,7 +42,12 @@ def enum(definitions)
_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] }
@@ -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

0 comments on commit 6c720d1

Please sign in to comment.