Class: ENVied::Coercer

Inherits:
Object
  • Object
show all
Defined in:
lib/envied/coercer.rb

Overview

Responsible for all string to type coercions.

Defined Under Namespace

Classes: ENViedString

Constant Summary collapse

UnsupportedCoercion =
Class.new(StandardError)

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.supported_type?(type) ⇒ Boolean

Whether or not Coercer can coerce strings to the provided type.

Examples:

ENVied::Coercer.supported_type?('string')
# => true

Parameters:

  • type (#to_sym)

    the type (case insensitive)

Returns:

  • (Boolean)

    whether type is supported.



38
39
40
# File 'lib/envied/coercer.rb', line 38

def self.supported_type?(type)
  supported_types.include?(type.to_sym.downcase)
end

.supported_typesObject



23
24
25
26
27
# File 'lib/envied/coercer.rb', line 23

def self.supported_types
  @supported_types ||= begin
    [:hash, :array, :time, :date, :symbol, :boolean, :integer, :string, :uri, :float].sort
  end
end

Instance Method Details

#coerce(string, type) ⇒ type

Coerce strings to specific type.

Examples:

ENVied::Coercer.new.coerce('1', :Integer)
# => 1

Parameters:

  • string (String)

    the string to be coerced

  • type (#to_sym)

    the type to coerce to

Returns:

  • (type)

    the coerced string.



16
17
18
19
20
21
# File 'lib/envied/coercer.rb', line 16

def coerce(string, type)
  unless supported_type?(type)
    raise ArgumentError, "The type `#{type.inspect}` is not supported."
  end
  coercer.public_send("to_#{type.downcase}", string)
end

#coerced?(value) ⇒ Boolean

Returns:

  • (Boolean)


54
55
56
# File 'lib/envied/coercer.rb', line 54

def coerced?(value)
  !value.kind_of?(String)
end

#coercerObject



50
51
52
# File 'lib/envied/coercer.rb', line 50

def coercer
  @coercer ||= ENViedString.new
end

#coercible?(string, type) ⇒ Boolean

Returns:

  • (Boolean)


58
59
60
61
62
63
64
# File 'lib/envied/coercer.rb', line 58

def coercible?(string, type)
  return false unless supported_type?(type)
  coerce(string, type)
  true
rescue UnsupportedCoercion
  false
end

#supported_type?(type) ⇒ Boolean

Returns:

  • (Boolean)


42
43
44
# File 'lib/envied/coercer.rb', line 42

def supported_type?(type)
  self.class.supported_type?(type)
end

#supported_typesObject



46
47
48
# File 'lib/envied/coercer.rb', line 46

def supported_types
  self.class.supported_types
end