Sha256: 9806f4403a63fa83b760a6c943814bda70a3ef23fc1a2f1d8e2ed370ca7c6b10

Contents?: true

Size: 712 Bytes

Versions: 9

Compression:

Stored size: 712 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.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

  end # Coercion
end # TTY

Version data entries

9 entries across 9 versions & 1 rubygems

Version Path
tty-0.0.11 lib/tty/support/coercion.rb
tty-0.0.10 lib/tty/support/coercion.rb
tty-0.0.9 lib/tty/support/coercion.rb
tty-0.0.8 lib/tty/support/coercion.rb
tty-0.0.7 lib/tty/support/coercion.rb
tty-0.0.6 lib/tty/support/coercion.rb
tty-0.0.5 lib/tty/support/coercion.rb
tty-0.0.4 lib/tty/support/coercion.rb
tty-0.0.3 lib/tty/support/coercion.rb