Module: TTY::Coercion

Included in:
Table::Operation::Alignment
Defined in:
lib/tty/support/coercion.rb

Overview

A mixin to coerce a value into a specific class.

Instance Method Summary collapse

Instance Method Details

#coerce_to(object, cls, method) ⇒ Object

Helper to coerce value into a specific class.

Parameters:

  • object (Object)
  • cls (Class)
  • method (Symbol)


16
17
18
19
20
21
22
23
24
25
26
27
28
# File 'lib/tty/support/coercion.rb', line 16

def coerce_to(object, cls, method)
  return object if object.kind_of?(cls)

  begin
    result = object.__send__(method)
  rescue Exception => e
    raise TypeError, "Coercion error #{e.message}"
  end
  unless result.kind_of? cls
    raise TypeError, "Coercion error: obj.#{method} did not return a #{cls} (was #{result.class})"
  end
  result
end