module Sequel::Plugins::Enum::ClassMethods

  1. lib/sequel/plugins/enum.rb

Methods

Public Instance

  1. enum

Public Instance methods

enum(column, values, opts=OPTS)

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

[show source]
    # File lib/sequel/plugins/enum.rb
 65 def enum(column, values, opts=OPTS)
 66   raise Sequel::Error, "enum column must be a symbol" unless column.is_a?(Symbol)
 67   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)}
 68 
 69   if prefix = opts[:prefix]
 70     prefix = column if prefix == true
 71     prefix = "#{prefix}_"
 72   end
 73 
 74   if suffix = opts[:suffix]
 75     suffix = column if suffix == true
 76     suffix = "_#{suffix}"
 77   end
 78   
 79   values = Hash[values].freeze
 80   inverted = values.invert.freeze
 81 
 82   unless @enum_methods
 83     @enum_methods = Module.new
 84     include @enum_methods
 85   end
 86 
 87   @enum_methods.module_eval do
 88     unless opts[:override_accessors] == false
 89       define_method(column) do
 90         v = super()
 91         inverted.fetch(v, v)
 92       end
 93 
 94       define_method(:"#{column}=") do |v|
 95         super(values.fetch(v, v))
 96       end
 97     end
 98 
 99     values.each do |key, value|
100       define_method(:"#{prefix}#{key}#{suffix}!") do
101         self[column] = value
102         nil
103       end
104 
105       define_method(:"#{prefix}#{key}#{suffix}?") do
106         self[column] == value
107       end
108     end
109   end
110 
111   unless opts[:dataset_methods] == false
112     dataset_module do
113       values.each do |key, value|
114         cond = Sequel[column=>value]
115         where :"#{prefix}#{key}#{suffix}", cond
116         where :"#{prefix}not_#{key}#{suffix}", ~cond
117       end
118     end
119   end
120 end