module Dry::Types::Coercions

Common coercion functions used by the built-in `Params` and `JSON` types

@api public

Public Instance Methods

to_date(input) { || ... } click to toggle source

@param [#to_str, Object] input

@return [Date, Object]

@see Date.parse

@api public

# File lib/dry/types/coercions.rb, line 18
def to_date(input, &block)
  if input.respond_to?(:to_str)
    begin
      ::Date.parse(input)
    rescue ArgumentError, RangeError => e
      CoercionError.handle(e, &block)
    end
  elsif input.is_a?(::Date)
    input
  elsif block_given?
    yield
  else
    raise CoercionError, "#{input.inspect} is not a string"
  end
end
to_date_time(input) { || ... } click to toggle source

@param [#to_str, Object] input

@return [DateTime, Object]

@see DateTime.parse

@api public

# File lib/dry/types/coercions.rb, line 41
def to_date_time(input, &block)
  if input.respond_to?(:to_str)
    begin
      ::DateTime.parse(input)
    rescue ArgumentError => e
      CoercionError.handle(e, &block)
    end
  elsif input.is_a?(::DateTime)
    input
  elsif block_given?
    yield
  else
    raise CoercionError, "#{input.inspect} is not a string"
  end
end
to_symbol(input, &block) click to toggle source

@param [#to_sym, Object] input

@return [Symbol, Object]

@raise CoercionError

@api public

# File lib/dry/types/coercions.rb, line 87
def to_symbol(input, &block)
  input.to_sym
rescue NoMethodError => e
  CoercionError.handle(e, &block)
end
to_time(input) { || ... } click to toggle source

@param [#to_str, Object] input

@return [Time, Object]

@see Time.parse

@api public

# File lib/dry/types/coercions.rb, line 64
def to_time(input, &block)
  if input.respond_to?(:to_str)
    begin
      ::Time.parse(input)
    rescue ArgumentError => e
      CoercionError.handle(e, &block)
    end
  elsif input.is_a?(::Time)
    input
  elsif block_given?
    yield
  else
    raise CoercionError, "#{input.inspect} is not a string"
  end
end

Private Instance Methods

empty_str?(value) click to toggle source

Checks whether String is empty

@param [String, Object] value

@return [Boolean]

@api private

# File lib/dry/types/coercions.rb, line 102
def empty_str?(value)
  EMPTY_STRING.eql?(value)
end