Last active
December 13, 2015 18:15
-
-
Save dreikanter/18c4917eda09d07fcce5 to your computer and use it in GitHub Desktop.
More meaningful ActiveRecord::Enum
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Enum | |
def self.value(key, value = nil) | |
@enum ||= {} | |
@enum[key] = value || @enum.size | |
define_singleton_method(key) { @enum[key] } | |
end | |
def self.enum | |
@enum | |
end | |
end | |
class Gender < Enum | |
value :undefined | |
value :male | |
value :female | |
end | |
class User < ActiveRecord::Base | |
enum gender: Gender.enum | |
end | |
User.new(gender: Gender.male) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Enum | |
def self.create(*args) | |
Class.new do | |
@enum = {} | |
define_singleton_method(:enum) { @enum } | |
args.each do |key| | |
@enum[key] = @enum.size | |
define_singleton_method(key) { @enum[key] } | |
end | |
end | |
end | |
end | |
Gender = Enum.create(:undefined, :male, :female) | |
class User < ActiveRecord::Base | |
enum gender: Gender.enum | |
end | |
User.new(gender: Gender.male) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Enum | |
def self.new(*args, **kwargs) | |
Class.new do | |
@enum = Hash[args.each_with_index.to_a].merge(kwargs || {}).freeze | |
@enum.each { |key, value| define_singleton_method(key) { value } } | |
define_singleton_method(:enum) { @enum } | |
end | |
end | |
end | |
Gender = Enum.new(undefined: 0, male: 1, female: 2) | |
class User < ActiveRecord::Base | |
enum gender: Gender.enum | |
end | |
User.new(gender: Gender.male) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment