Module: ClassyEnum::Collection::ClassMethods

Includes:
Enumerable
Defined in:
lib/classy_enum/collection.rb

Instance Method Summary collapse

Instance Method Details

#eachObject

Iterates over instances of each enum in the collection

Example

Create an Enum with some elements

class Priority < ClassyEnum::Base end

class Priority::Low < Priority; end class Priority::Medium < Priority; end class Priority::High < Priority; end

Priority.each do |priority| puts priority # => 'Low', 'Medium', 'High' end



81
82
83
# File 'lib/classy_enum/collection.rb', line 81

def each
  enum_options.each {|e| yield e.new }
end

#find(key = nil) ⇒ Object Also known as: detect, []

Finds an enum instance by symbol, string, or block.

If a block is given, it passes each entry in enum to block, and returns the first enum for which block is not false. If no enum matches, it returns nil.

Example

Create an Enum with some elements

class Priority < ClassyEnum::Base end

class Priority::Low < Priority; end class Priority::Medium < Priority; end class Priority::High < Priority; end

Priority.find(:high) # => Priority::High.new Priority.find('high') # => Priority::High.new Priority.find {|e| e.to_sym == :high } # => Priority::High.new



119
120
121
122
123
124
125
# File 'lib/classy_enum/collection.rb', line 119

def find(key=nil)
  if block_given?
    super
  elsif map(&:to_s).include? key.to_s
    super { |e| e.to_s == key.to_s }
  end
end

#inherited(klass) ⇒ Object



47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
# File 'lib/classy_enum/collection.rb', line 47

def inherited(klass)
  if self == ClassyEnum::Base
    klass.class_eval do
      def self.enum_options
        @enum_options ||= superclass.enum_options
      end

      def self.enum_options=(options)
        @enum_options = options
      end
    end
    klass.enum_options = []
  else
    enum_options << klass
    klass.instance_variable_set('@index', enum_options.size)
  end

  super
end

#lastObject

Returns the last enum instance in the collection

Example

Create an Enum with some elements

class Priority < ClassyEnum::Base end

class Priority::Low < Priority; end class Priority::Medium < Priority; end class Priority::High < Priority; end

Priority.last # => Priority::High



97
98
99
# File 'lib/classy_enum/collection.rb', line 97

def last
  to_a.last
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 end

class Priority::Low < Priority; end class Priority::ReallyHigh < Priority; end

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



142
143
144
# File 'lib/classy_enum/collection.rb', line 142

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