I’d like to ask if people have thoughts on clean ways of making
behaviour in the model depend on attributes of the request.
Things I’m thinking of:
-
per-user Time.zone (currently handled by setting a thread-local
variable in the controller) -
created_by and updated_by fields. Googling around, the recommended
way seems to be the same, set Thread.current[‘user’] = session[:user]
in a before filter -
updated_ip (i.e. logging request.ip when a model is saved). Ditto.
-
when I do a bulk update from a controller, I’d like all the
updated_at timestamps to be exactly the same (when using millisecond-
accurate timestamps), so as to allow the changes to be grouped in a
query (“group by updated_at”). That means taking a snapshot of the
current time, and using it in all the model updates for the duration
of that request.
It seems to me that doing all this via Thread-local variables is a bit
icky. For one thing, you have to remember to erase them before each
new request. And if you take it to the extreme, you might be tempted
to do
Thread[‘session’] = session
Thread[‘request’] = request
etc, possibly burying things like access-control logic in the model.
I’d be interested to hear if anyone has implemented a cleaner way for
the model layer to make limited callbacks to the controller layer, and
how you designed it.
I think you’d want an object which exposes methods that are not made
public on the controller itself (because you don’t want them
accessible from the outside world). Thinking aloud:
class FooController < ApplicationController
class Callback
def initialize(ctrl)
@ctrl = ctrl
end
def time
@time ||= Time.now
end
def zone
@zone ||= @ctrl.instance_eval { session[:tz] }
end
def ip
@ip ||= @ctrl.instance_eval { request.ip }
end
before do
Thread.current[‘callback’] = Callback.new(self)
end
end
Any better ideas?