0

How do I see / 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.)

2
  • 1
    I wouldn't be using threads like this personally. If you have a long running process, using a scheduler or queue is the way to go. Commented Jan 27, 2010 at 0:21
  • @Toby: Yes, agreed. Don't thread if you don't have to. DelayedJob or something similar should work better here. Commented Jan 28, 2010 at 18:03

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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?

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.