Module: DynamicVars

Defined in:
lib/dynamic_vars.rb

Class Method Summary collapse

Class Method Details

.[](key) ⇒ Object



37
38
39
# File 'lib/dynamic_vars.rb', line 37

def [](key)
  variables[key]
end

.[]=(key, value) ⇒ Object



41
42
43
# File 'lib/dynamic_vars.rb', line 41

def []=(key, value)
  variables[key] = value
end

.here!Object



7
8
9
10
11
# File 'lib/dynamic_vars.rb', line 7

def here!
  Thread.current[:DYNAMIC] = Hash.new { |hash, key|
    raise NameError, "no such dynamic variable: #{key}"
  }.update Thread.main[:DYNAMIC]
end

.let(bindings, &block) ⇒ Object



52
53
54
55
56
57
58
59
60
61
62
63
# File 'lib/dynamic_vars.rb', line 52

def let(bindings, &block)
  save = {}
  bindings.to_hash.collect { |key, value|
    save[key] = self[key]
    self[key] = value
  }
  begin
    block.call
  ensure
    variables.update save
  end
end

.method_missing(name, *args) ⇒ Object



65
66
67
68
69
70
71
72
73
# File 'lib/dynamic_vars.rb', line 65

def method_missing(name, *args)
  if match = /=\Z/.match(name.to_s)    # setter?
    raise ArgumentError, "invalid setter call"  unless args.size == 1
    self[match.pre_match.intern] = args.first
  else
    raise ArgumentError, "invalid getter call"  unless args.empty?
    self[name]
  end
end

.undefine(*keys) ⇒ Object



45
46
47
48
49
50
# File 'lib/dynamic_vars.rb', line 45

def undefine(*keys)
  keys.each { |key|
    self[key]
    variables.delete key
  }
end

.variable(definition) ⇒ Object



17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
# File 'lib/dynamic_vars.rb', line 17

def variable(definition)
  case definition
  when Symbol
    if variables.has_key? definition
      raise NameError, "dynamic variable `#{definition}' already exists"
    end
    variables[definition] = nil
  when Hash
    definition.each { |key, value|
      if variables.has_key? key
        raise NameError, "dynamic variable `#{key}' already exists"
      end
      variables[key] = value
    }
  else
    raise ArgumentError,
    "can't create a new dynamic variable from #{definition.class}"
  end
end

.variablesObject



13
14
15
# File 'lib/dynamic_vars.rb', line 13

def variables
  Thread.current[:DYNAMIC] or here!
end