require 'facets/core/hash/having_fallback'

class Hash

  # Define a fallback object for #fetch and #[].
  #
  #   f = Hash[:b=>2]
  #   h = Hash[:a=>1].having_aquisition(f)
  #   h[:b] => 2

  def with_aquisition(fallback)
    @fallback = fallback
    unless @fallsback
      def self.[](key)
        begin
          return @fallback[key] if @fallback and not key?(key)
        rescue
        end
        val = super
        val.fallback(self) if Hash == val
        val
      end
      def self.fetch(key, *args, &blk)
        begin
          return @fallback.fetch(key, *args, &blk) if @fallback and not key?(key)
        rescue
        end
        val = super
        val.fallback(self) if Hash == val
        val
      end
      @fallsback = true
    end
    self
  end

end
