Class: Virtus::Coercion::Object

Inherits:
Virtus::Coercion show all
Defined in:
lib/virtus/coercion/object.rb

Overview

Coerce Object values

Direct Known Subclasses

Array, Date, DateTime, FalseClass, Hash, Numeric, String, Symbol, Time, TrueClass

Constant Summary collapse

COERCION_METHOD_REGEXP =
/\Ato_/.freeze

Constants included from TypeLookup

TypeLookup::TYPE_FORMAT

Class Method Summary collapse

Methods inherited from Virtus::Coercion

[]

Methods included from TypeLookup

#determine_type, extended, #primitive

Methods included from Options

#accept_options, #accepted_options, #options

Class Method Details

.to_array(value) ⇒ Array

Create an Array from any Object

Examples:

with an object that does not respond to #to_a or #to_ary

Virtus::Coercion::Object.to_array(value)         # => [ value ]

with an object that responds to #to_a

Virtus::Coercion::Object.to_array(Set[ value ])  # => [ value ]

with n object that responds to #to_ary

Virtus::Coercion::Object.to_array([ value ])     # => [ value ]

Parameters:

  • value (#to_a, #to_ary, Object)
  • value (#to_a, #to_ary, Object)

Returns:



27
28
29
# File 'lib/virtus/coercion/object.rb', line 27

def self.to_array(value)
  Array(value)
end

.to_hash(value) ⇒ Hash, Object

Create a Hash from the Object if possible

Examples:

with a coercible object

Virtus::Coercion::Object.to_hash(key => value)  # => { key => value }

with an object that is not coercible

Virtus::Coercion::Object.to_hash(value)  # => value

Parameters:

Returns:

  • (Hash)

    returns a Hash when the object can be coerced

  • (Object)

    returns the value when the object cannot be coerced



47
48
49
# File 'lib/virtus/coercion/object.rb', line 47

def self.to_hash(value)
  coerce_with_method(value, :to_hash)
end

.to_integer(value) ⇒ Integer, Object

Create an Integer from the Object if possible

Examples:

with a coercible object

Virtus::Coercion::Object.to_integer(1)  # => 1

with an object that is not coercible

Virtus::Coercion::Object.to_integer(value)  # => value

Parameters:

Returns:

  • (Integer)

    returns an Integer when the object can be coerced

  • (Object)

    returns the value when the object cannot be coerced



87
88
89
# File 'lib/virtus/coercion/object.rb', line 87

def self.to_integer(value)
  coerce_with_method(value, :to_int)
end

.to_string(value) ⇒ String, Object

Create a String from the Object if possible

Examples:

with a coercible object

Virtus::Coercion::Object.to_string("string")  # => "string"

with an object that is not coercible

Virtus::Coercion::Object.to_string(value)  # => value

Parameters:

Returns:

  • (String)

    returns a String when the object can be coerced

  • (Object)

    returns the value when the object cannot be coerced



67
68
69
# File 'lib/virtus/coercion/object.rb', line 67

def self.to_string(value)
  coerce_with_method(value, :to_str)
end