Posted on November 30, 2011 - Filed Under RubyOnRails
Long time since last post, isn’t it? Well, I’m completely busy with my work in Nettigo, selling Arduinos and other nice gears :) I do not do gigs anymore, so there is a lot less reasons to write about Rails.
But I still use this framework, since my backend software is written in Rails, so here is one thing which I think can be useful for You.
Often we want to pass ID of current user to Rails model internals. Most answers are don’t do that, this is controller work to do authorization stuff, MVC is to prevent such thins, etc.
here was not related picture (as usual on this blog). Some readers were complaining it was not only unrelated but even offending. Well, maybe they were right, so, I have removed that picture.
Yeah, right, but what if we want to keep some kind of audit trail what is happening with given model? This is not authorization, just who done what.
Since in my application case audit records are created in observers simple passing user id as some additional parameter is no go for me – I don’t want to change interface just to pass user info, that breaks too much things.
So, I have chosen this approach:
def with_user user, &block if user.blank? yield else Thread.current[:user] = user.id yield Thread.current[:user] = nil end end
And each operation I want to track I invoke:
with_user(current_user) do model.do_some_stuff end
Thread.current acts as a hash accessible in current thread and allow us to pass some info skipping MVC isolation (You wanted that, right? :) )
In observers I can access user ID and store it with record. If it is not present, audit trails is being marked as created by System. That means probably cron job, or console action (well on console I can run code inside
with_user block when needed).
This is safe as long each request is being processed in single thread and we make sure that user ID will be cleared after our operation. When ID will stay in Thread.current, next request being processed by this Rails app instance will have access to that value and wrong audit records will be created.
Code has to be updated, since any exception will occur inside block, code after
yield will be skipped and user ID won’t be erased from
Thread.current. Here it is, final version:
def with_user user, &block if user.blank? yield else Thread.current[:user] = user.id begin yield ensure Thread.current[:user] = nil end end end
ensure will be executed each time – both when exception was raised and when execution was clean.
Popularity: 38% [?]
Hits for this post: 45169
- Logger – simple, yet powerful Rails debugging tool
- Skinny controller, fat model and Facebook
- Are ActiveRecord validations worth anything?
- Beginners life with Ruby and Rails
- Ups and downs with samba