Sha256: 52cd4fa85944e5eef1bb05d5051d2c65d7c74be657d5239e02fe878b64d22b5e

Contents?: true

Size: 1.58 KB

Versions: 1

Compression:

Stored size: 1.58 KB

Contents

# The MethodicHash is some method_missing magic that uses method names as hash
# keys, so hash assignment and lookup appear to be attribute writing and
# reading. For instance, if
#
#   mh = MethodicHash.new
#   mh['four']  = 'iv'
#   mh[:seven]  = 'vii'
#   mh.eighteen = 'xviii'
#
# then
#
#   mh['four']     ---> 'iv'
#   mh[:four]      ---> 'iv'
#   mh.four        ---> 'iv'
#   mh['seven']    ---> 'vii'
#   mh[:seven]     ---> 'vii'
#   mh.seven       ---> 'vii'
#   mh['eighteen'] ---> 'xviii'
#   mh[:eighteen]  ---> 'xviii'
#   mh.eighteen    ---> 'xviii'
#
# This allows access to simply declared facts to be embedded in Ruby code and
# leverages the possibility of hashing procs.
#
# Note that if the hash uses anything but strings or symbols as keys, the
# magic stands a good chance of failing, raising an error or acting in a
# bizarre manner. Note also that methods of the Hash cannot be used as
# 'attribute' names.
class MethodicHash < Hash
  
  # Try to look up using a key directly, or if that fails as a string, or as
  # a symbol as last resort. If a symbol conversion doesn't exists, rescue
  # with a nil.
  def [](key)
    begin
      super(key) || super(key.to_s) || super(key.to_sym)
    rescue
      nil
    end
  end
  
  # A missing method is assummed to be the assignment of a value of a key, or
  # the lookup of a value with a key.
  def method_missing(method,*args)
    string = method.to_s
    if string[string.length-1,1] == '='
      self[string[0,string.length-1].to_sym] = args[0]
    else
      self[method]
    end
  end

end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
eymiha_util-0.1.3 lib/methodic_hash.rb