Skip to content
This repository was archived by the owner on Oct 19, 2018. It is now read-only.

Commit b38cbf2

Browse files
committed
more flexibility with Context.reset
1 parent 75eb031 commit b38cbf2

File tree

1 file changed

+19
-13
lines changed

1 file changed

+19
-13
lines changed

lib/hyperloop/context.rb

Lines changed: 19 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -5,26 +5,32 @@ module Hyperloop
55
# the provided block will be rerun and the instance variable re-initialized
66
# when the reset! method is called
77
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)
1421
end
1522

1623
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
1825
# 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) }
2430
end
2531
Hyperloop::Application::Boot.run if reboot
2632
else
27-
@context_hash = {}
33+
@context = Hash.new { |h, k| h[k] = {} }
2834
end
2935
end
3036
end

0 commit comments

Comments
 (0)