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

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.



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

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

.supported_typesObject



27
28
29
30
31
# File 'lib/envied/coercer.rb', line 27

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.



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

def coerce(string, type)
  unless supported_type?(type)
    raise ArgumentError, "#{type.inspect} is not supported type"
  end
  coerce_method_for(type.to_sym)[string]
end

#coerce_method_for(type) ⇒ Object



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

def coerce_method_for(type)
  return nil unless supported_type?(type)
  coercer.method("to_#{type.downcase}")
end

#coerced?(value) ⇒ Boolean

Returns:

  • (Boolean)


58
59
60
# File 'lib/envied/coercer.rb', line 58

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

#coercerObject



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

def coercer
  @coercer ||= Coercible::Coercer.new[ENViedString]
end

#coercible?(string, type) ⇒ Boolean

Returns:

  • (Boolean)


62
63
64
65
66
67
68
# File 'lib/envied/coercer.rb', line 62

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

#supported_type?(type) ⇒ Boolean

Returns:

  • (Boolean)


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

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

#supported_typesObject



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

def supported_types
  self.class.supported_types
end