Module: ClassyEnum::ClassMethods

Defined in:
lib/classy_enum/class_methods.rb

Instance Method Summary collapse

Instance Method Details

#allObject

Returns an array of all instantiated enums

Example

# Create an Enum with some elements
class Priority < ClassyEnum::Base
  enum_classes :low, :medium, :high
end

Priority.all # => [PriorityLow.new, PriorityMedium.new, PriorityHigh.new]


30
31
32
# File 'lib/classy_enum/class_methods.rb', line 30

def all
  self::OPTIONS.map {|e| build(e) }
end

#build(option) ⇒ Object Also known as: find

Build a new ClassyEnum child instance

Example

# Create an Enum with some elements
class Priority < ClassyEnum::Base
  enum_classes :low, :medium, :high
end

Priority.build(:low) # => PriorityLow.new


13
14
15
16
17
# File 'lib/classy_enum/class_methods.rb', line 13

def build(option)
  return option if option.blank?
  return TypeError.new("Valid #{self} options are #{self.valid_options}") unless self::OPTIONS.include? option.to_sym
  Object.const_get("#{self}#{option.to_s.camelize}").new
end

#select_optionsObject

Returns a 2D array for Rails select helper options. Also used internally for Formtastic support

Example

# Create an Enum with some elements
class Priority < ClassyEnum::Base
  enum_classes :low, :really_high
end

Priority.select_options # => [["Low", "low"], ["Really High", "really_high"]]


44
45
46
# File 'lib/classy_enum/class_methods.rb', line 44

def select_options
  all.map {|e| [e.name, e.to_s] }
end

#valid_optionsObject

Returns a comma separated list of valid enum options. Also used internally for ActiveRecord model validation error messages

Example

# Create an Enum with some elements
class Priority < ClassyEnum::Base
  enum_classes :low, :medium, :high
end

Priority.valid_options # => "low, medium, high"


58
59
60
# File 'lib/classy_enum/class_methods.rb', line 58

def valid_options
  self::OPTIONS.map(&:to_s).join(', ')
end