Class: Iora::Coercer

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

Overview

Coercer converts string values to Ruby objects like integers and arrays. It is used internally for reading XML data. For example:

Coercer.coerce('true').to(Boolean) # => true
Coercer.coerce('48.7').to(Float) # => 48.7
Coercer.coerce('cats, dogs').to(Array) # => ['cats', 'dogs']

There are coercers for Array, Float, Integer, String, and Symbol. There is also a coercer for Iora::Boolean, an empty class for designating coercion to a boolean value.

Instance Method Summary collapse

Constructor Details

#initialize(str) ⇒ Coercer

Create a new Coercer for a string.

Parameters:

  • str (String)

Raises:

  • (ArgumentError)

20
21
22
23
# File 'lib/iora/coercer.rb', line 20

def initialize(str)
  raise ArgumentError unless str.is_a?(String) || str.nil?
  @str = str
end

Instance Method Details

#to(klass) ⇒ Object

Convert the string to a given class.

Parameters:

  • klass (Class)

Returns:

  • (Object)

34
35
36
37
# File 'lib/iora/coercer.rb', line 34

def to(klass)
  return nil unless @str.present?
  send("to_#{klass.name.demodulize.downcase}")
end