Class: Interdependence::ActiveModel::ValidatesWith

Inherits:
Object
  • Object
show all
Defined in:
lib/interdependence/activemodel/validates_with.rb

Overview

Handler for ‘validates_with` method calls intended for ActiveModel

Makes it easy to iterate over attributes, options, and validators.

Examples:

when given attributes

class FancyValidator < ActiveModel::EachValidator; end

with = ValidatesWith.new(
  FancyValidator,
  thing: :yes,
  attributes: i(foo bar)
)

with.attributes? # => true
>> with.each # => #<Enumerator: ...>

with.each.to_a # => [
#   [[:foo, FancyValidator], {:thing=>:yes}],
#   [[:bar, FancyValidator], {:thing=>:yes}]
# ]

when no attributes

with = ValidatesWith.new(
  FancyValidator,
  thing: :yes,
  attributes: []
)

>> with.attributes? # => false
>> with.each.to_a # => []

Instance Method Summary collapse

Constructor Details

#initialize(*args) ⇒ undefined

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

Handle arguments intended for #validates_with



41
42
43
44
# File 'lib/interdependence/activemodel/validates_with.rb', line 41

def initialize(*args)
  @validators = args
  @options = @validators.extract_options!
end

Instance Method Details

#attributes?boolean

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

Any attributes present

Returns:

  • (boolean)

    if any attributes were given



81
82
83
# File 'lib/interdependence/activemodel/validates_with.rb', line 81

def attributes?
  attributes.any?
end

#each(&blk) ⇒ undefined

Iterate over fields and validators

with.each do |(attribute, validator), options|
  puts [attribute, validator.kind, options].inspect
end

#=> [:foo, :presence, :thing=>:yes] #=> [:foo, :numericality, :thing=>:yes] #=> [:bar, :presence, :thing=>:yes] #=> [:bar, :numericality, :thing=>:yes]

Examples:

usage

with = ValidatesWith.new(
  PresenceValidator,
  NumericalityValidator,
  thing: :yes,
  attributes: i(foo bar)
)

Returns:

  • (undefined)


69
70
71
72
73
# File 'lib/interdependence/activemodel/validates_with.rb', line 69

def each(&blk)
  attributes_with_validators
    .each
    .with_object(options, &blk)
end