module Contracts::Formatters::InspectWrapper

A wrapper class to produce correct inspect behaviour for different contract values - constants, Class contracts, instance contracts etc.

Public Class Methods

create(value, full: true) click to toggle source

InspectWrapper is a factory, will never be an instance @return [ClassInspectWrapper, ObjectInspectWrapper]

# File lib/contracts/formatters.rb, line 48
def self.create(value, full: true)
  if value.instance_of?(Class)
    ClassInspectWrapper
  else
    ObjectInspectWrapper
  end.new(value, full)
end
new(value, full) click to toggle source

@param full [Boolean] if false only unique `to_s` values will be output,

non unique values become empty string.
# File lib/contracts/formatters.rb, line 58
def initialize(value, full)
  @value, @full = value, full
end

Public Instance Methods

delim(value) click to toggle source
# File lib/contracts/formatters.rb, line 76
def delim(value)
  @full ? "(#{value})" : "#{value}"
end
inspect() click to toggle source

Inspect different types of contract values. Contracts module prefix will be removed from classes. Custom to_s messages will be wrapped in round brackets to differentiate from standard Strings. Primitive values e.g. 42, true, nil will be left alone.

# File lib/contracts/formatters.rb, line 67
def inspect
  return "" unless full?
  return @value.inspect if empty_val?
  return @value.to_s if plain?
  return delim(@value.to_s) if useful_to_s?

  useful_inspect
end
to_s() click to toggle source

Eliminates eronious quotes in output that plain inspect includes.

# File lib/contracts/formatters.rb, line 81
def to_s
  inspect
end

Private Instance Methods

empty_to_s?() click to toggle source
# File lib/contracts/formatters.rb, line 107
def empty_to_s?
  @value.to_s.empty?
end
empty_val?() click to toggle source
# File lib/contracts/formatters.rb, line 87
def empty_val?
  @value.nil? || @value == ""
end
full?() click to toggle source
# File lib/contracts/formatters.rb, line 91
def full?
  @full ||
    @value.is_a?(Hash) || @value.is_a?(Array) ||
    (!plain? && useful_to_s?)
end
plain?() click to toggle source
# File lib/contracts/formatters.rb, line 97
def plain?
  # Not a type of contract that can have a custom to_s defined
  !@value.is_a?(Builtin::CallableClass) && @value.class != Class
end
strip_prefix(val) click to toggle source
# File lib/contracts/formatters.rb, line 111
def strip_prefix(val)
  val.gsub(/^Contracts::Builtin::/, "")
end
useful_to_s?() click to toggle source
# File lib/contracts/formatters.rb, line 102
def useful_to_s?
  # Useless to_s value or no custom to_s behaviour defined
  !empty_to_s? && custom_to_s?
end