How do I see / 开发者_JAVA百科change session data from within a thread within rails? See this code snippet inside my controller:
def controller_action
session[:something] = 'before' # works properly
Thread.new do
session[:something] = 'after' # out of scope. <--- how do I fix this?
end
end
(related to this question, but much more specific. I expect quite different answers.)
Why do you need to change session data in a background thread?
Are you using the default cookie store, because if you are I'm not sure how this would work. If you were to switch to the memcached/database session store you might have more luck as you can access the session after the request has finished.
I'm still not sure why session would not be in scope by reference inside a thread, but if this is true, you could try passing the current binding to the thread as an argument:
Thread.new(binding) do
thread_session = eval("session", binding)
end
Or something like that. I'm still not convinced that the session is by value and not by reference in the Thread. To check this I just passed some hashes into new threads on the console, and changes made to a hash inside a thread are visible outside that thread. Is there some magic that makes session behave differently?
EDIT: Wouldn't DelayedJob be a better way to handle a long-running process spun off from a user request?
精彩评论