Sha256: e999123e913876c6f816560ff76cbb7a80582352ca4b0bfddd62e0a1f402ef02

Contents?: true

Size: 778 Bytes

Versions: 4

Compression:

Stored size: 778 Bytes

Contents

module Hotcell
  class Scope
    def initialize scope = {}
      @scope = [scope]
    end

    def [] key
      cache[key]
    end

    def []= key, value
      clear_cache
      hash = scope.reverse_each.detect { |hash| hash.key? key }
      hash ||= scope.last
      hash[key] = value
    end

    def key? key
      cache.key?(key)
    end

    def push data
      cache.merge!(data)
      scope.push(data)
    end

    def pop
      clear_cache
      scope.pop if scope.size > 1
    end

    def scoped data
      push(data)
      yield
    ensure
      pop
    end

  private

    def scope
      @scope
    end

    def reduce
      scope.inject({}, &:merge)
    end

    def cache
      @cache ||= reduce
    end

    def clear_cache
      @cache = nil
    end
  end
end

Version data entries

4 entries across 4 versions & 1 rubygems

Version Path
hotcell-0.3.0 lib/hotcell/scope.rb
hotcell-0.2.0 lib/hotcell/scope.rb
hotcell-0.1.0 lib/hotcell/scope.rb
hotcell-0.0.1 lib/hotcell/scope.rb