Sha256: 427e4954d4ddd23afe7171f3f19d4a6b8691c8c64db99b248aa4bec414129c21

Contents?: true

Size: 725 Bytes

Versions: 11

Compression:

Stored size: 725 Bytes

Contents

# encoding: utf-8

module TTY
  # A mixin to coerce a value into a specific class.
  module Coercion
    # Helper to coerce value into a specific class.
    #
    # @param [Object] object
    #
    # @param [Class] cls
    #
    # @param [Symbol] method
    #
    # @api public
    def coerce_to(object, cls, method)
      return object if object.is_a?(cls)

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

Version data entries

11 entries across 11 versions & 1 rubygems

Version Path
tty-0.5.0 lib/tty/support/coercion.rb
tty-0.4.0 lib/tty/support/coercion.rb
tty-0.3.2 lib/tty/support/coercion.rb
tty-0.3.1 lib/tty/support/coercion.rb
tty-0.3.0 lib/tty/support/coercion.rb
tty-0.2.1 lib/tty/support/coercion.rb
tty-0.2.0 lib/tty/support/coercion.rb
tty-0.1.3 lib/tty/support/coercion.rb
tty-0.1.2 lib/tty/support/coercion.rb
tty-0.1.1 lib/tty/support/coercion.rb
tty-0.1.0 lib/tty/support/coercion.rb