Sha256: 9a7bc0341f4b9b022df480891cb189768720263311d49e88c120203b77480357

Contents?: true

Size: 1.52 KB

Versions: 1

Compression:

Stored size: 1.52 KB

Contents

# This file contains very lightweight, generally useful additions and
# modifications to the ruby core classes. While the additions should be no
# problem, and the modifications are not significantly obtrusive, they may
# present a problem if there are overlaps or dependencies.
#
# I use these in much of my code; you may find them useful too.

# Provides a general method raising on conversion problems.
class Object
  
  # Raises an TypeError with a human-readable message when the instance src
  # cannot be converted to an instance of type dest.
  def raise_no_conversion(src,dest=self)
    dest = dest.class.name unless dest.instance_of? String
    raise TypeError, "Cannot convert '#{src.class.name}' to #{dest}"
  end
  
  # Returns the class name of a class or an instance.
  def class_name
    (instance_of? Class) ? self.name : self.class.name
  end
  
  # Optionally require a library - don't fail if it's missing.
  def optional_require feature
    begin
      require feature
    rescue LoadError
    end
  end
  
end


# Provides simple a ruby-oriented string conversion.
class Hash
  
  alias to_s_old to_s
  
  # a simple string conversion for hashes.
  def to_s
    strings = []
    each_pair { |key, value| strings << "#{key} => #{value}" }
    "{ #{strings.join ", "} }"
  end
  
end


# Provides a ruby-oriented array conversion.
class Array
  
  alias to_s_old to_s
  
  # a simple string conversion for arrays.
  def to_s()
    strings = []
    each { |member| strings << "#{member}" }
    "[ #{strings.join ", "} ]"
  end
  
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
eymiha-1.0.0 lib/eymiha.rb