mgsnova/crisp

View on GitHub
lib/crisp/env.rb

Summary

Maintainability
A
0 mins
Test Coverage
module Crisp
  # The Crisp environment is basically a key/value store.
  # The value for each key is immutable, so you can only store one time for each key
  class Env
    attr_accessor :global_loop_data

    # create a new internal hash
    def initialize
      @map = {}
    end

    # Returns boolean for existence of given key in the environment.
    def has_key?(key)
      @map.has_key?(key.to_sym)
    end

    # Returns the value for the given key.
    def [](key)
      result = @map[key.to_sym]

      if result.class == Hash and result[:alias_to]
        self[result[:alias_to]]
      else
        result
      end
    end

    # Store the key/value pair.
    # It is only possible to store a value for a key once, otherwise a error will be raised.
    def []=(key, val)
      key = key.to_sym
      raise EnvironmentError, "#{key} already binded" if @map.has_key?(key)
      @map[key] = val
    end

    # Store alias
    def alias(to, from)
      self[to] = {:alias_to => from}
    end
  end
end