Module: ArrayEnum

Defined in:
lib/array_enum.rb,
lib/array_enum/version.rb

Defined Under Namespace

Classes: Railtie, SubsetValidator

Constant Summary collapse

VERSION =
'1.6.0'

Instance Method Summary collapse

Instance Method Details

#array_enum(definitions) ⇒ Object



11
12
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
# File 'lib/array_enum.rb', line 11

def array_enum(definitions)
  definitions.each do |attr_name, mapping|
    attr_symbol = attr_name.to_sym
    mapping_hash = ActiveSupport::HashWithIndifferentAccess.new(mapping)

    define_singleton_method(attr_name.to_s.pluralize) do
      mapping_hash
    end

    {
      "with_#{attr_name}" => '@>',
      "only_with_#{attr_name}" => '=',
      "with_any_of_#{attr_name}" => '&&'
    }.each do |method_name, comparison_operator|
      define_singleton_method(method_name.to_sym) do |values|
        db_values = Array(values).map do |value|
          mapping_hash[value] || raise(ArgumentError, format(MISSING_VALUE_MESSAGE, value: value, attr: attr_name))
        end
        where("#{table_name}.#{attr_name} #{comparison_operator} ARRAY[:db_values]::integer[]", db_values: db_values)
      end
    end

    define_method(attr_symbol) do
      Array(self[attr_symbol]).map { |value| mapping_hash.key(value) }
    end

    define_method("#{attr_name}=".to_sym) do |values|
      self[attr_symbol] = Array(values).map do |value|
        mapping_hash[value] || raise(ArgumentError, format(MISSING_VALUE_MESSAGE, value: value, attr: attr_name))
      end.uniq
    end
  end
end