Created
September 21, 2016 05:17
-
-
Save ichi/e91b2059d95fbce04ab1f786600f941d to your computer and use it in GitHub Desktop.
railsのenumにも使えるやーつ
This file contains 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 ApplicationEnum | |
class << self | |
attr_writer :attribute_names | |
def all | |
@all ||= Set.new | |
end | |
def attribute_names | |
@attribute_names ||= Set.new | |
end | |
def enums | |
all.map{|e| [e.key, e.id] }.to_h | |
end | |
def [](k) | |
all.find{|e| e.is? k } | |
end | |
def define(**attributes) | |
all << new(**attributes) | |
end | |
end | |
attr_reader :id, :key | |
def initialize(id:, key:, **attributes) | |
attributes.symbolize_keys! | |
self.class.attribute_names += Set[*attributes.keys] | |
@id, @key, @attributes = id, key.to_s, attributes.with_indifferent_access | |
end | |
def method_missing(name, *args) | |
if self.class.attribute_names.include? name.to_sym | |
@attributes[name] | |
else | |
super | |
end | |
end | |
def is?(k) | |
id == k || key == k.to_s | |
end | |
def eql?(other) | |
@id == other.id | |
end | |
def hash | |
@id.hash | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment