Method: ClassyEnum::ClassMethods#enum_classes
- Defined in:
- lib/classy_enum/class_methods.rb
#enum_classes(*enums) ⇒ Object
Macro for defining enum members within a ClassyEnum class. Accepts an array of symbols or strings which are converted to ClassyEnum members as descents of their parent class.
Example
# Define an enum called Priority with three child classes
class Priority < ClassyEnum::Base
enum_classes :low, :medium, :high
end
The child classes will be defined with the following constants:
PriorityLow, PriorityMedium, and PriorityHigh
These child classes can be instantiated with either:
Priority.build(:low) or PriorityLow.new
20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 |
# File 'lib/classy_enum/class_methods.rb', line 20 def enum_classes(*enums) self.const_set("OPTIONS", enums) unless self.const_defined? "OPTIONS" enums.each_with_index do |option, index| klass = Class.new(self) do @index = index + 1 @option = option attr_accessor :owner, :serialize_as_json # Use ActiveModel::AttributeMethods to define attribute? methods attribute_method_suffix '?' define_attribute_methods enums end klass_name = "#{self}#{option.to_s.camelize}" Object.const_set(klass_name, klass) unless Object.const_defined? klass_name end end |