Sha256: 7fd53cd93095162e12209d68598b3ce8c8e9a0b6e11ed05e35868f396e85d210

Contents?: true

Size: 1.17 KB

Versions: 5

Compression:

Stored size: 1.17 KB

Contents

module Loquor
  class ObjectHashKeyMissingError < LoquorError
  end

  class ObjectHash
    def initialize(hash, options = {})
      @hash = hash
      @strict = options[:strict]
    end

    def ==(other)
      if other.is_a?(ObjectHash)
        @hash == other.get_instance_variable(:@hash)
      elsif other.is_a?(Hash)
        @hash == other
      else
        false
      end
    end

    def [](key)
      fetch_indescriminately(key)
    rescue ObjectHashKeyMissingError
      if @strict
        raise $!
      else
        nil
      end
    end

    def method_missing(name, *args)
      if name[-1] == "="
        @hash.send(name, *args) 
      else
        self[name]
      end
    end

    private

    def fetch_indescriminately(name, *args)
      if @hash.has_key?(name)
        @hash[name]
      elsif @hash.has_key?(name.to_s)
        @hash[name.to_s]
      elsif @hash.has_key?(name.to_s.to_sym)
        @hash[name.to_s.to_sym]
      else
        raise ObjectHashKeyMissingError.new(name)
      end
    end
  end
end

class Hash
  alias_method :hash_equals, :==
  def ==(other)
    if other.is_a?(Loquor::ObjectHash)
      other == self
    else
      hash_equals(other)
    end
  end
end

Version data entries

5 entries across 5 versions & 1 rubygems

Version Path
loquor-1.0.0 lib/loquor/object_hash.rb
loquor-0.9.0 lib/loquor/object_hash.rb
loquor-0.8.0 lib/loquor/object_hash.rb
loquor-0.7.0 lib/loquor/object_hash.rb
loquor-0.6.0 lib/loquor/object_hash.rb