Module: EnumType

Defined in:
lib/enum_type.rb

Overview

Adds the @enum_type@ method to a model.

Examples:

Basic usage

class MyModel < ActiveRecord::Base
  extend EnumType
  enum_type :status, values: %w( open closed flagged deleted )
end

Instance Method Summary collapse

Instance Method Details

#enum_type(field, ..., options = {}) ⇒ Object

Defines a field whose type is an enumeration. Values are stored as strings in the backend (or your database’s enumerated type), however in the Rails level they are represented as symbols.

Examples:

Enumerated field with restricted types

enum_type :color, values: %w( red orange yellow green blue purple )

is allowed. to those in the given array.

Parameters:

  • field (Symbol)

    An enumerated field.

  • options (Hash) (defaults to: {})

    A hash of options.

Options Hash (options):

  • :allow_nil (true, false) — default: false

    If @true@, a nil value

  • :values (Array<String>)

    If given, restricts valid values



28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
# File 'lib/enum_type.rb', line 28

def enum_type(*fields)
  options = fields.extract_options!
  fields.each do |field|
    define_method field do
      value = read_attribute(field)
      value ? value.to_sym : value
    end

    define_method :"#{field}=" do |value|
      write_attribute field, value.try(:to_s)
    end

    validates_presence_of(field) unless options[:allow_nil]
    validates_inclusion_of(field, in: options[:values].map(&:to_sym), allow_nil: options[:allow_nil]) if options[:values]
  end
end