# Callbacks from model to request?

**URL:** <https://www.ruby-forum.com/t/callbacks-from-model-to-request/181278>\
**Category:** Rails\
**Created:** [January 8, 2010, 5:41pm UTC](https://www.ruby-forum.com/t/callbacks-from-model-to-request/181278 "2010-01-08T17:41:12Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

**Author:** ![stickstone](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/s/6f9a4e/32.png) [@stickstone](https://www.ruby-forum.com/u/stickstone)\
**Post date:** [January 8, 2010, 5:41pm UTC](https://www.ruby-forum.com/t/callbacks-from-model-to-request/181278/1 "2010-01-08T17:41:12Z")

</div>

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?
