Reputation: 18139
Is there a way to scope variables to the thread without having to pass everything around, given a class with the following methods:
def initialize
@server = TCPServer.new('localhost',456)
end
def start
threads = []
while (upload = @server.accept)
threads << Thread.new(upload) do |connection|
some_method_here(connection)
end
end
threads.each {|t| t.join }
end
def some_method_here(connection)
variable = "abc"
another_method(connection,variable)
end
def another_method(connection,variable)
puts variable.inspect
connection.close
end
Upvotes: 1
Views: 1766
Reputation: 178
You can try an around_filter in ApplicationController
around_filter :apply_scope
def apply_scope
Document.where(:user_id => current_user.id).scoping do
yield
end
Upvotes: 0
Reputation: 6030
if I get you right you want to use thread local variables (see the ruby rdoc for Thread#[])
From the rdoc:
a = Thread.new { Thread.current["name"] = "A"; Thread.stop }
b = Thread.new { Thread.current[:name] = "B"; Thread.stop }
c = Thread.new { Thread.current["name"] = "C"; Thread.stop }
Thread.list.each {|x| puts "#{x.inspect}: #{x[:name]}" }
produces:
#<Thread:0x401b3b3c sleep>: C
#<Thread:0x401b3bc8 sleep>: B
#<Thread:0x401b3c68 sleep>: A
#<Thread:0x401bdf4c run>:
So your example would use
Thread.current[:variable] = "abc"
Thread.current[:variable] # => "abc"
wherever you were using just variable
before
Upvotes: 6