class Shoulda::Matchers::ActiveRecord::AssociationMatchers::OptionalMatcher

@private

Attributes

attribute_name[R]
missing_option[R]
optional[R]
submatcher[R]

Public Class Methods

new(attribute_name, optional) click to toggle source
# File lib/shoulda/matchers/active_record/association_matchers/optional_matcher.rb, line 9
def initialize(attribute_name, optional)
  @attribute_name = attribute_name
  @optional = optional
  @submatcher = ActiveModel::AllowValueMatcher.new(nil).
    for(attribute_name)
  @missing_option = ''
end

Public Instance Methods

description() click to toggle source
# File lib/shoulda/matchers/active_record/association_matchers/optional_matcher.rb, line 17
def description
  "optional: #{optional}"
end
matches?(subject) click to toggle source
# File lib/shoulda/matchers/active_record/association_matchers/optional_matcher.rb, line 21
def matches?(subject)
  if submatcher_passes?(subject)
    true
  else
    @missing_option = 'and for the record '

    missing_option <<
      if optional
        'not to '
      else
        'to '
      end

    missing_option << (
      'fail validation if ' +
      ":#{attribute_name} is unset; i.e., either the association " +
      'should have been defined with `optional: ' +
      "#{optional.inspect}`, or there "
    )

    missing_option <<
      if optional
        'should not '
      else
        'should '
      end

    missing_option << "be a presence validation on :#{attribute_name}"

    false
  end
end

Private Instance Methods

submatcher_passes?(subject) click to toggle source
# File lib/shoulda/matchers/active_record/association_matchers/optional_matcher.rb, line 58
def submatcher_passes?(subject)
  if optional
    submatcher.matches?(subject)
  else
    submatcher.does_not_match?(subject)
  end
end