Module: Sequel::Plugins::Enum::ClassMethods

Defined in:
lib/sequel/plugins/enum.rb

Instance Method Summary collapse

Instance Method Details

#enum(column, values, opts = OPTS) ⇒ Object

Define instance and dataset methods in this class to treat column as a enum. See Enum documentation for usage.

Raises:



65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
# File 'lib/sequel/plugins/enum.rb', line 65

def enum(column, values, opts=OPTS)
  raise Sequel::Error, "enum column must be a symbol" unless column.is_a?(Symbol)
  raise Sequel::Error, "enum values must be provided as a hash with symbol keys" unless values.is_a?(Hash) && values.all?{|k,| k.is_a?(Symbol)}

  if prefix = opts[:prefix]
    prefix = column if prefix == true
    prefix = "#{prefix}_"
  end

  if suffix = opts[:suffix]
    suffix = column if suffix == true
    suffix = "_#{suffix}"
  end
  
  values = Hash[values].freeze
  inverted = values.invert.freeze

  unless @enum_methods
    @enum_methods = Module.new
    include @enum_methods
  end

  @enum_methods.module_eval do
    unless opts[:override_accessors] == false
      define_method(column) do
        v = super()
        inverted.fetch(v, v)
      end

      define_method(:"#{column}=") do |v|
        super(values.fetch(v, v))
      end
    end

    values.each do |key, value|
      define_method(:"#{prefix}#{key}#{suffix}!") do
        self[column] = value
        nil
      end

      define_method(:"#{prefix}#{key}#{suffix}?") do
        self[column] == value
      end
    end
  end

  unless opts[:dataset_methods] == false
    dataset_module do
      values.each do |key, value|
        cond = Sequel[column=>value]
        where :"#{prefix}#{key}#{suffix}", cond
        where :"#{prefix}not_#{key}#{suffix}", ~cond
      end
    end
  end
end