Module: Dynamic::ClassMethods
- Included in:
- Dynamic
- Defined in:
- lib/ext/dynamic.rb
Overview
Instance Method Summary
collapse
Dynamic Method Handling
This class handles dynamic methods through the method_missing method
#method_missing(name, *args) ⇒ Object
73
74
75
76
77
78
79
80
81
|
# File 'lib/ext/dynamic.rb', line 73
def method_missing(name, *args)
if match = /=\Z/.match(name.to_s) 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
|
Instance Method Details
47
48
49
|
# File 'lib/ext/dynamic.rb', line 47
def [](key)
variables[key]
end
|
#[]=(key, value) ⇒ Object
51
52
53
|
# File 'lib/ext/dynamic.rb', line 51
def []=(key, value)
variables[key] = value
end
|
17
18
19
20
21
|
# File 'lib/ext/dynamic.rb', line 17
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
62
63
64
65
66
67
68
69
70
71
|
# File 'lib/ext/dynamic.rb', line 62
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
55
56
57
58
59
60
|
# File 'lib/ext/dynamic.rb', line 55
def undefine(*keys)
keys.each { |key|
self[key]
variables.delete key
}
end
|
#variable(definition) ⇒ Object
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
|
# File 'lib/ext/dynamic.rb', line 27
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
|
#variables ⇒ Object
23
24
25
|
# File 'lib/ext/dynamic.rb', line 23
def variables
Thread.current[:DYNAMIC] or here!
end
|