Module: RecordNotUnique::ClassMethods

Defined in:
lib/record_not_unique.rb

Instance Method Summary collapse

Instance Method Details

#handle_record_not_unique(*args) ⇒ Object



5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
# File 'lib/record_not_unique.rb', line 5

def handle_record_not_unique(*args)
  # need to be shared across child classes as indexes would be common
  class_eval do
    cattr_accessor :_rnu_indexes, :_rnu_error_messages
    
    self._rnu_indexes = []
    self._rnu_error_messages = []
    _indexes = connection.indexes(table_name)
    args.each do |arg|
      raise NotImplementedError unless arg.key?(:field) && arg.key?(:message)
      raise 'field should be an array' unless arg[:field].is_a?(Array)
      _index = _indexes.detect { |index| index.columns.eql?(arg[:field]) }
      raise "Couldn't find unique index for field #{arg[:field].join(',')}" if !_index&.unique
      self._rnu_indexes << _index.name
      self._rnu_error_messages << arg[:message].to_a.flatten
    end
    prepend InstanceMethods
  end
end