Sha256: b98a9e01eecbee345eee7368c68d171a1f6ad9fb3467b93f747c619fc2df3e7b

Contents?: true

Size: 1.72 KB

Versions: 8

Compression:

Stored size: 1.72 KB

Contents

module Shoulda
  module Matchers
    module ActiveRecord
      module AssociationMatchers
        # @private
        class OptionalMatcher
          attr_reader :missing_option

          def initialize(attribute_name, optional)
            @attribute_name = attribute_name
            @optional = optional
            @submatcher = ActiveModel::AllowValueMatcher.new(nil).
              for(attribute_name)
            @missing_option = ''
          end

          def description
            "optional: #{optional}"
          end

          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

          attr_reader :attribute_name, :optional, :submatcher

          def submatcher_passes?(subject)
            if optional
              submatcher.matches?(subject)
            else
              submatcher.does_not_match?(subject)
            end
          end
        end
      end
    end
  end
end

Version data entries

8 entries across 8 versions & 1 rubygems

Version Path
shoulda-matchers-4.4.1 lib/shoulda/matchers/active_record/association_matchers/optional_matcher.rb
shoulda-matchers-4.4.0 lib/shoulda/matchers/active_record/association_matchers/optional_matcher.rb
shoulda-matchers-4.3.0 lib/shoulda/matchers/active_record/association_matchers/optional_matcher.rb
shoulda-matchers-4.2.0 lib/shoulda/matchers/active_record/association_matchers/optional_matcher.rb
shoulda-matchers-4.1.2 lib/shoulda/matchers/active_record/association_matchers/optional_matcher.rb
shoulda-matchers-4.1.1 lib/shoulda/matchers/active_record/association_matchers/optional_matcher.rb
shoulda-matchers-4.1.0 lib/shoulda/matchers/active_record/association_matchers/optional_matcher.rb
shoulda-matchers-4.0.1 lib/shoulda/matchers/active_record/association_matchers/optional_matcher.rb