Class: DMatch::Env

Inherits:
Object show all
Defined in:
lib/destructure/env.rb

Defined Under Namespace

Classes: EnvNil

Instance Method Summary collapse

Instance Method Details

#[](identifier) ⇒ Object



12
13
14
15
16
17
18
19
20
# File 'lib/destructure/env.rb', line 12

def [](identifier)
  raise 'identifier must be a Var or symbol' unless (identifier.is_a? Var) || (identifier.is_a? Symbol)
  if identifier.is_a? Symbol
    identifier = env.keys.select{|k| k.name == identifier}.first || identifier
  end
  v = env[identifier]
  raise "Identifier '#{identifier}' is not bound." if v.nil?
  v.is_a?(EnvNil) ? nil : v
end

#bind(identifier, value) ⇒ Object Also known as: []=



22
23
24
25
26
27
28
29
30
31
# File 'lib/destructure/env.rb', line 22

def bind(identifier, value)
  raise 'identifier must be a Var' unless identifier.is_a? Var
  value_to_store = value.nil? ? EnvNil.new : value
  existing_key = env.keys.select{|k| k == identifier || (k.name.is_a?(Symbol) && k.name == identifier.name)}.first
  return nil if existing_key &&
      (DMatch.match(env[existing_key], value_to_store).nil? ||
      DMatch.match(value_to_store, env[existing_key]).nil?)
  env[existing_key || identifier] = value_to_store
  self
end

#envObject



8
9
10
# File 'lib/destructure/env.rb', line 8

def env
  @env ||= {}
end

#keysObject



35
36
37
# File 'lib/destructure/env.rb', line 35

def keys
  env.keys
end

#merge!(other_env) ⇒ Object



43
44
45
# File 'lib/destructure/env.rb', line 43

def merge!(other_env)
  other_env.keys.any?{|k| bind(k, other_env[k]).nil?} ? nil : self
end

#to_openstructObject



39
40
41
# File 'lib/destructure/env.rb', line 39

def to_openstruct
  OpenStruct.new(Hash[env.map{|kv| [kv.first.name, kv.last]}])
end