Module: Dynamic::ClassMethods

Included in:
Dynamic
Defined in:
lib/dynamic.rb

Overview

:nodoc:

Class Method Summary collapse

Instance Method Summary collapse

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(name, *args) ⇒ Object



80
81
82
83
84
85
86
87
88
# File 'lib/dynamic.rb', line 80

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

Class Method Details

.main_dynamicsObject



17
18
19
20
21
# File 'lib/dynamic.rb', line 17

def main_dynamics
  @main_dynamics ||= Hash.new { |hash, key|
    raise NameError, "no such dynamic variable: #{key}"
  }
end

Instance Method Details

#[](key) ⇒ Object



54
55
56
# File 'lib/dynamic.rb', line 54

def [](key)
  variables[key]
end

#[]=(key, value) ⇒ Object



58
59
60
# File 'lib/dynamic.rb', line 58

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

#here!Object



24
25
26
27
28
# File 'lib/dynamic.rb', line 24

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

#let(bindings, &block) ⇒ Object



69
70
71
72
73
74
75
76
77
78
# File 'lib/dynamic.rb', line 69

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

#undefine(*keys) ⇒ Object



62
63
64
65
66
67
# File 'lib/dynamic.rb', line 62

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

#variable(definition) ⇒ Object



34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
# File 'lib/dynamic.rb', line 34

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



30
31
32
# File 'lib/dynamic.rb', line 30

def variables
  Thread.current == Thread.main ? ClassMethods.main_dynamics : Thread.current[:DYNAMIC] or here!
end