Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
A way to track the current block level for instance block-methods, which is completely thread-safe
class MyObject
def block_depth=(value)
Thread.current[:block_depth] = value
end
def block_depth
Thread.current[:block_depth] || 0
end
def track_block_depth(&block)
self.block_depth += 1
yield
ensure
self.block_depth -= 1
end
def method1(stuff, &block)
track_block_depth do
puts "This is #{stuff}... #{self.block_depth} level deep\n"
yield
end
end
def method2(stuff, &block)
track_block_depth do
puts "This is #{stuff}... #{self.block_depth} levels deep\n"
yield
end
end
end
obj = MyObject.new
t1 = Thread.new do
obj.method1 "something" do
obj.method2 "something else" do
puts "hiya\n"
end
puts "Back to #{obj.block_depth} level deep\n"
end
end
t2 = Thread.new do
obj.method1 "something" do
obj.method2 "something else" do
puts "hiya\n"
end
puts "Back to #{obj.block_depth} level deep\n"
end
end
t1.join
t2.join
# => This is something... 1 level deep
# => This is something... 1 level deep
# => This is something else... 2 levels deep
# => This is something else... 2 levels deep
# => hiya
# => hiya
# => Back to 1 level deep
# => Back to 1 level deep
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment