Skip to content

Commit

Permalink
make enums distinct per class
Browse files Browse the repository at this point in the history
  • Loading branch information
vanwhale committed Apr 7, 2014
1 parent c45939e commit bbe7fe4
Show file tree
Hide file tree
Showing 3 changed files with 28 additions and 4 deletions.
7 changes: 7 additions & 0 deletions activerecord/CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,10 @@
* Fixed a problem where an enum would overwrite values of another enum
with the same name in an unrelated class.

Fixes #14607.

*Evan Whalen*

* PostgreSQL and SQLite string columns no longer have a default limit of 255.

Fixes #13435, #9153.
Expand Down
10 changes: 6 additions & 4 deletions activerecord/lib/active_record/enum.rb
Original file line number Diff line number Diff line change
Expand Up @@ -65,10 +65,13 @@ module ActiveRecord
#
# Where conditions on an enum attribute must use the ordinal value of an enum.
module Enum
DEFINED_ENUMS = {} # :nodoc:
def self.extended(base)
base.class_attribute(:defined_enums)
base.defined_enums = {}
end

def enum_mapping_for(attr_name) # :nodoc:
DEFINED_ENUMS[attr_name.to_s]
defined_enums[attr_name.to_s]
end

def enum(definitions)
Expand Down Expand Up @@ -122,9 +125,8 @@ def enum(definitions)
klass.send(:detect_enum_conflict!, name, value, true)
klass.scope value, -> { klass.where name => i }
end

DEFINED_ENUMS[name.to_s] = enum_values
end
defined_enums[name.to_s] = enum_values
end
end

Expand Down
15 changes: 15 additions & 0 deletions activerecord/test/cases/enum_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -250,4 +250,19 @@ def self.name; 'Book'; end
valid_book = klass.new(status: "written")
assert valid_book.valid?
end

test "enums are distinct per class" do
Plane = Class.new(ActiveRecord::Base) do
enum status: [:grounded, :operational]
end
assert_equal({ "proposed" => 0, "written" => 1, "published" => 2 }, Book.statuses)
assert_equal({ "grounded" => 0, "operational" => 1 }, Plane.statuses)
end

test "enums are inheritable" do
Encyclopedia = Class.new(Book) do
enum status: [:published, :reprinted]
end
assert_equal({ "published" => 0, "reprinted" => 1 }, Encyclopedia.statuses)
end
end

0 comments on commit bbe7fe4

Please sign in to comment.