Sha256: ef6fc60de784d6ee90bb131b4931992cc5cbf3a06f7a1c8901d153e96e7fa91d

Contents?: true

Size: 1.25 KB

Versions: 48

Compression:

Stored size: 1.25 KB

Contents

# frozen_string_literal: true

module Ree::Contracts
  module ArgContracts
    class RangeOf
      extend Ree::Contracts::ArgContracts::Squarable
      include Ree::Contracts::Truncatable

      attr_reader :validator
      
      def initialize(*contracts)
        if contracts.size != 1
          raise BadContractError, 'RangeOf should accept exactly one contract'
        end

        @validator = Validators.fetch_for(contracts.first)
      end

      def valid?(value)
        value.is_a?(Range) &&
          validator.call(value.begin) &&
          validator.call(value.end)
      end

      def to_s
        "RangeOf[#{validator.to_s}]"
      end

      def message(value, name, lvl = 1)
        unless value.is_a?(Range)
          return "expected Range, got #{value.class} => #{truncate(value.inspect)}"
        end

        errors = []
        sps = "  " * lvl

        unless validator.call(value.begin)
          msg = validator.message(value.begin, "#{name}.begin", lvl + 1)
          errors << "\n\t#{sps} - #{name}.begin: #{msg}"
        end

        unless validator.call(value.end)
          msg = validator.message(value.end, "#{name}.end", lvl + 1)
          errors << "\n\t#{sps} - #{name}.end: #{msg}"
        end

        errors.join
      end
    end
  end
end

Version data entries

48 entries across 48 versions & 1 rubygems

Version Path
ree-1.0.47 lib/ree/contracts/arg_contracts/range_of.rb
ree-1.0.46 lib/ree/contracts/arg_contracts/range_of.rb
ree-1.0.45 lib/ree/contracts/arg_contracts/range_of.rb
ree-1.0.44 lib/ree/contracts/arg_contracts/range_of.rb
ree-1.0.43 lib/ree/contracts/arg_contracts/range_of.rb
ree-1.0.42 lib/ree/contracts/arg_contracts/range_of.rb
ree-1.0.41 lib/ree/contracts/arg_contracts/range_of.rb
ree-1.0.40 lib/ree/contracts/arg_contracts/range_of.rb
ree-1.0.39 lib/ree/contracts/arg_contracts/range_of.rb
ree-1.0.38 lib/ree/contracts/arg_contracts/range_of.rb
ree-1.0.37 lib/ree/contracts/arg_contracts/range_of.rb
ree-1.0.36 lib/ree/contracts/arg_contracts/range_of.rb
ree-1.0.35 lib/ree/contracts/arg_contracts/range_of.rb
ree-1.0.34 lib/ree/contracts/arg_contracts/range_of.rb
ree-1.0.33 lib/ree/contracts/arg_contracts/range_of.rb
ree-1.0.32 lib/ree/contracts/arg_contracts/range_of.rb
ree-1.0.31 lib/ree/contracts/arg_contracts/range_of.rb
ree-1.0.30 lib/ree/contracts/arg_contracts/range_of.rb
ree-1.0.29 lib/ree/contracts/arg_contracts/range_of.rb
ree-1.0.28 lib/ree/contracts/arg_contracts/range_of.rb