module ArrayEnum

Constants

MISSING_VALUE_MESSAGE
VERSION

Public Instance Methods

array_enum(definitions) click to toggle source
# 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

    define_singleton_method("with_#{attr_name}".to_sym) do |values|
      db_values = Array(values).map do |value|
        mapping_hash[value] || raise(ArgumentError, MISSING_VALUE_MESSAGE % {value: value, attr: attr_name})
      end
      where("#{attr_name} @> ARRAY[:db_values]", db_values: db_values)
    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, MISSING_VALUE_MESSAGE % {value: value, attr: attr_name})
      end.uniq
    end
  end
end