Module: Backframe::ActsAsEnum::ClassMethods

Defined in:
lib/backframe/activerecord/acts_as_enum.rb

Instance Method Summary collapse

Instance Method Details

#acts_as_enum(*args) ⇒ Object



13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
# File 'lib/backframe/activerecord/acts_as_enum.rb', line 13

def acts_as_enum(*args)

  field = args[0]
  arguments = args[1]

  if arguments.key?(:required)

    validates_presence_of field

  end

  if arguments.key?(:default)

    after_initialize "init_#{field}".to_sym, :if => Proc.new { |d| d.new_record? }

    class_eval <<-EOV
      def init_#{field}
        self.#{field} ||= '#{arguments[:default]}'
      end
    EOV

  end

  if arguments.key?(:in)

    validates_inclusion_of field, :in => arguments[:in]

    class_eval <<-EOV
      scope :#{field}_is, -> (*options) { where('"#{self.table_name}"."#{field}" IN (?)', (options.is_a?(Array) ? options : [options])) }

      def #{field}_is?(*options)
        (options.is_a?(Array) ? options : [options]).map(&:to_s).include?(self.#{field})
      end
    EOV

    class_eval <<-EOV
      scope :#{field}_not, -> (*options) { where('"#{self.table_name}"."#{field}" NOT IN (?)', (options.is_a?(Array) ? options : [options])) }

      def #{field}_not?(*options)
        !(options.is_a?(Array) ? options : [options]).map(&:to_s).include?(self.#{field})
      end
    EOV

  end

end