Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse files

Explicit mapping for enum

  • Loading branch information...
commit 7caa09c5e1833ccc6b209a71588a44fb91606246 1 parent 0944792
@yury yury authored
View
6 activerecord/lib/active_record/enum.rb
@@ -3,6 +3,9 @@ module ActiveRecord
#
# class Conversation < ActiveRecord::Base
# enum status: [:active, :archived]
+ #
+ # # same but with explicit mapping
+ # enum status: {active: 0, archived: 1}
# end
#
# Conversation::STATUS # => { active: 0, archived: 1 }
@@ -41,7 +44,8 @@ def enum(definitions)
# def direction() DIRECTION.key self[:direction] end
class_eval "def #{name}() #{const_name}.key self[:#{name}] end"
- values.each_with_index do |value, i|
+ pairs = values.respond_to?(:each_pair) ? values.each_pair : values.each_with_index
+ pairs.each do |value, i|
# DIRECTION[:incoming] = 0
const_get(const_name)[value] = i
View
8 activerecord/test/cases/enum_test.rb
@@ -12,14 +12,18 @@ class StoreTest < ActiveRecord::TestCase
assert @book.proposed?
assert_not @book.written?
assert_not @book.published?
+
+ assert @book.unread?
end
test "query state with symbol" do
assert_equal :proposed, @book.status
+ assert_equal :unread, @book.read_status
end
test "find via scope" do
assert_equal @book, Book.proposed.first
+ assert_equal @book, Book.unread.first
end
test "update by declaration" do
@@ -36,5 +40,9 @@ class StoreTest < ActiveRecord::TestCase
assert_equal 0, Book::STATUS[:proposed]
assert_equal 1, Book::STATUS[:written]
assert_equal 2, Book::STATUS[:published]
+
+ assert_equal 0, Book::READ_STATUS[:unread]
+ assert_equal 2, Book::READ_STATUS[:reading]
+ assert_equal 3, Book::READ_STATUS[:read]
end
end
View
1  activerecord/test/models/book.rb
@@ -8,4 +8,5 @@ class Book < ActiveRecord::Base
has_many :subscribers, through: :subscriptions
enum status: [:proposed, :written, :published]
+ enum read_status: {unread: 0, reading: 2, read: 3}
end
View
1  activerecord/test/schema/schema.rb
@@ -95,6 +95,7 @@ def create_table(*args, &block)
t.integer :author_id
t.column :name, :string
t.column :status, :integer, default: 0
+ t.column :read_status, :integer, default: 0
end
create_table :booleans, :force => true do |t|
Please sign in to comment.
Something went wrong with that request. Please try again.