Sha256: 93f3dd89f08754709c701ebb8d728486c415993c07d2ef5bbfd543bc39411093

Contents?: true

Size: 1.42 KB

Versions: 4

Compression:

Stored size: 1.42 KB

Contents

# frozen_string_literal: true

module Matchi
  class BeWithin
    # *BeWithin of* matcher.
    class Of
      # @return [Numeric] An expected value.
      attr_reader :expected

      # Initialize the matcher with a delta and an expected value.
      #
      # @example
      #   require "matchi/be_within/of"
      #
      #   Matchi::BeWithin::Of.new(1, 41)
      #
      # @param delta    [Numeric] The accepted variation of the actual value.
      # @param expected [Numeric] The expected value.
      def initialize(delta, expected)
        @delta    = delta
        @expected = expected
      end

      # Boolean comparison on the expected be_within by comparing the actual
      # value and the expected value.
      #
      # @example
      #   require "matchi/be_within/of"
      #
      #   matcher = Matchi::BeWithin::Of.new(1, 41)
      #
      #   matcher.expected        # => 41
      #   matcher.matches? { 42 } # => true
      #
      # @yieldreturn [Numeric] The block of code to execute.
      #
      # @return [Boolean] Comparison between the actual and the expected values.
      def matches?
        (expected - yield).abs <= @delta
      end

      # A string containing a human-readable representation of the matcher.
      def inspect
        "#{self.class}(#{@delta}, #{expected})"
      end

      # Returns a string representing the matcher.
      def to_s
        "be within #{@delta} of #{expected}"
      end
    end
  end
end

Version data entries

4 entries across 4 versions & 1 rubygems

Version Path
matchi-3.3.2 lib/matchi/be_within/of.rb
matchi-3.3.1 lib/matchi/be_within/of.rb
matchi-3.3.0 lib/matchi/be_within/of.rb
matchi-3.2.0 lib/matchi/be_within/of.rb