Module: WithResources
- Defined in:
- lib/with_resources.rb,
lib/with_resources/version.rb
Defined Under Namespace
Modules: ErrorExt, TopLevel
Constant Summary
collapse
- VERSION =
"0.1.0"
Class Method Summary
collapse
Class Method Details
.with(allocation, release_method: :close, &block) ⇒ Object
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
|
# File 'lib/with_resources.rb', line 10
def self.with(allocation, release_method: :close, &block)
var_names = []
vars = {}
allocation_block_path = nil
allocation_block_lineno = nil
trace = TracePoint.new(:line, :b_return) do |tp|
if tp.event == :line && !tp.path.end_with?("lib/with_resources.rb") && allocation_block_path.nil?
allocation_block_path = tp.path
allocation_block_lineno = tp.lineno
end
if tp.event == :line && tp.path == allocation_block_path && tp.lineno >= allocation_block_lineno
tp_binding = tp.binding
tp_variables = tp_binding.local_variables
if var_names.all?{|resource_var| tp_variables.include?(resource_var) }
tp_variables.each do |name|
unless var_names.include?(name)
var_names << name
end
end
end
end
if tp.event == :b_return && tp.path == allocation_block_path && tp.lineno >= allocation_block_lineno
tp_binding = tp.binding
var_names.each do |name|
vars[name] = tp_binding.local_variable_get(name)
end
end
end
error = nil
return_value = nil
begin
trace.enable do
allocation.call
end
return_value = block.call(*vars.values)
rescue => e
error = e
error.extend(ErrorExt)
ensure
vars.values.reverse.each do |v|
if v.respond_to?(release_method)
begin
v.send(release_method)
rescue => e
if error
error.suppressed << e
else
error = e
error.extend(ErrorExt)
end
end
end
end
end
raise error if error
return_value
end
|