Sha256: 56217eabbc95752cea65f31eea8e870c00856fba52c4c8e6527d617fa37bd39b

Contents?: true

Size: 1.97 KB

Versions: 14

Compression:

Stored size: 1.97 KB

Contents

module Opal
  def self.type_error(object, type, method = nil, coerced = nil)
    if method && coerced
      TypeError.new "can't convert #{object.class} into #{type} (#{object.class}##{method} gives #{coerced.class}"
    else
      TypeError.new "no implicit conversion of #{object.class} into #{type}"
    end
  end

  def self.coerce_to(object, type, method)
    return object if type === object

    unless object.respond_to? method
      raise type_error(object, type)
    end

    object.__send__ method
  end

  def self.coerce_to!(object, type, method)
    coerced = coerce_to(object, type, method)

    unless type === coerced
      raise type_error(object, type, method, coerced)
    end

    coerced
  end

  def self.coerce_to?(object, type, method)
    return unless object.respond_to? method

    coerced = coerce_to(object, type, method)

    return if coerced.nil?

    unless type === coerced
      raise type_error(object, type, method, coerced)
    end

    coerced
  end

  def self.try_convert(object, type, method)
    return object if type === object

    if object.respond_to? method
      object.__send__ method
    end
  end

  def self.compare(a, b)
    compare = a <=> b

    if `compare === nil`
      raise ArgumentError, "comparison of #{a.class} with #{b.class} failed"
    end

    compare
  end

  def self.destructure(args)
    %x{
      if (args.length == 1) {
        return args[0];
      }
      else if (args.$$is_array) {
        return args;
      }
      else {
        return $slice.call(args);
      }
    }
  end

  def self.respond_to?(obj, method)
    %x{
      if (obj == null || !obj.$$class) {
        return false;
      }
    }

    obj.respond_to? method
  end

  def self.inspect(obj)
    %x{
      if (obj === undefined) {
        return "undefined";
      }
      else if (obj === null) {
        return "null";
      }
      else if (!obj.$$class) {
        return obj.toString();
      }
      else {
        return #{obj.inspect};
      }
    }
  end
end

Version data entries

14 entries across 14 versions & 2 rubygems

Version Path
opal-0.8.1 opal/corelib/helpers.rb
opal-0.8.1.rc1 opal/corelib/helpers.rb
opal-wedge-0.9.0.dev opal/corelib/helpers.rb
opal-0.8.0 opal/corelib/helpers.rb
opal-0.8.0.rc3 opal/corelib/helpers.rb
opal-0.8.0.rc2 opal/corelib/helpers.rb
opal-0.8.0.rc1 opal/corelib/helpers.rb
opal-0.8.0.beta1 opal/corelib/helpers.rb
opal-0.7.2 opal/corelib/helpers.rb
opal-0.7.1 opal/corelib/helpers.rb
opal-0.7.0 opal/corelib/helpers.rb
opal-0.7.0.rc1 opal/corelib/helpers.rb
opal-0.7.0.beta3 opal/corelib/helpers.rb
opal-0.7.0.beta2 opal/corelib/helpers.rb