@@ -5,26 +5,32 @@ module Hyperloop
5
5
# the provided block will be rerun and the instance variable re-initialized
6
6
# when the reset! method is called
7
7
module Context
8
- # pass self, an instance var name (symbol) and a block
9
- # if reset! has been called, then record the var and block for future resets
10
- # then if var is currently empty it will be initialized with block
11
- def self . set_var ( ctx , var , &block )
12
- @context_hash [ ctx ] ||= [ var , block ] if @context_hash
13
- ctx . instance_variable_get ( var ) || ctx . instance_variable_set ( var , yield )
8
+ # Replace @foo ||= ... with
9
+ # Context.set_var(self, :@foo) { ... }
10
+ # If reset! has been called then the instance variable will be record, and
11
+ # will be reset on the next call to reset!
12
+ # If you want to record the current value of the instance variable then set
13
+ # force to true.
14
+ def self . set_var ( ctx , var , force : nil )
15
+ puts "calling set_var(#{ var } )"
16
+ inst_value_b4 = ctx . instance_variable_get ( var )
17
+ if @context && !@context [ ctx ] . key? ( var ) && ( force || !inst_value_b4 )
18
+ @context [ ctx ] [ var ] = ( inst_value_b4 && inst_value_b4 . dup )
19
+ end
20
+ inst_value_b4 || ctx . instance_variable_set ( var , yield )
14
21
end
15
22
16
23
def self . reset! ( reboot = true )
17
- # if @context_hash is already initialized then reset all the instance
24
+ # if @context is already initialized then reset all the instance
18
25
# vars using their corresponding blocks. Otherwise initialize
19
- # @context_hash.
20
- if @context_hash
21
- @context_hash . each do |context , var_and_block |
22
- var , block = var_and_block
23
- context . instance_variable_set ( var , block . call )
26
+ # @context.
27
+ if @context
28
+ @context . each do |ctx , vars |
29
+ vars . each { |var , init | ctx . instance_variable_set ( var , init ) }
24
30
end
25
31
Hyperloop ::Application ::Boot . run if reboot
26
32
else
27
- @context_hash = { }
33
+ @context = Hash . new { | h , k | h [ k ] = { } }
28
34
end
29
35
end
30
36
end
0 commit comments