Module: ActiveTools::ActiveModel::ValidWith::ClassMethods

Defined in:
lib/active_tools/active_model/valid_with.rb

Instance Method Summary collapse

Instance Method Details

#valid_with(*args) ⇒ Object



8
9
10
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
# File 'lib/active_tools/active_model/valid_with.rb', line 8

def valid_with(*args)
  options = args.extract_options!
  object_name = args.first
  passed_attr_map = options.delete(:attributes)||{}
  prefix = options.delete(:prefix)
  attr_map_name = :"_valid_with_#{object_name}"
  unless respond_to?(attr_map_name)
    class_attribute attr_map_name 
    self.send("#{attr_map_name}=", passed_attr_map.with_indifferent_access)
  else
    self.send(attr_map_name).merge!(passed_attr_map)
  end

  validate(*[options]) do
    if object = send(object_name)
      if options[:fit] == true
        object.instance_variable_set(:@errors, ActiveTools::ActiveModel::ValidWith::FakeErrors.new(object))
      end
      if !object.valid?
        object.errors.messages.each do |attribute, suberrors|
          local_attribute = send(attr_map_name)[attribute]||attribute
          suberrors.each do |suberror|
            errors.add([prefix.to_s, local_attribute].select(&:present?).join("_"), suberror)
          end
        end
      end
    end
  end
end