2

This question is related to: Access current_user in model.

Specifically, I want to enable access to current_user in one Model.rb. @moif left a comment stating that the solution is not thread-safe, and I have read that there are additional caveats to using this process.

My question is this - if I were to add:

def self.current_user
    Thread.local[:current_user]
end

def self.current_user=(usr)
    Thread.local[:current_user] = usr
end

to one Model.rb (used only lightly and infrequently), what are the real-world implications for my app and is there anything additional I have to do to ensure its health?

Set up: Rails 1.9, Rails 3.0, Heroku, Authlogic.

Community
  • 1
  • 1
sscirrus
  • 55,407
  • 41
  • 135
  • 228
  • Good question. I'm interested in seeing the answers. I've faced this on my current project and really don't like using the thread object to pass around variables--I'm doing it similarly to what you have above and it leaves me feeling...dirty. – jaydel Jun 27 '11 at 23:23

1 Answers1

1

I'm not sure I agree about the path you are taking. I agree with the other post that passing the current_user to the model is not appropriate but I wouldn't be using Thread.local for that. Here's why:

  1. Developers love to get technical with solutions and there's not much more "closer to the system" you can get than a Thread.local. Having used Thread.locals before they are very tricky and if you don't get it right then you spend countless hours trying to figure out the problem let alone the solution. It also is difficult to find testers who can understand the complexities of Thread.local and be able to test the code thoroughly. In fact I would wonder how many developers put together solid rspec tests (or equivalent) for something like this. The "cost" of this solution may not be worth it.

  2. I think I would take a look at what you are trying to do and see if there is an easier solution. For example, I can think of two off-hand (maybe would work or not in your case):

a) connect your history table to your user table with a foreign key. "belongs_to, has_many"; or
b) pass the username with attr_accessor on history and set that when creating the object.

Arthur Frankel
  • 4,695
  • 6
  • 35
  • 56