Passing current user id to Rails models

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?
    Thread.current[:user] =
    Thread.current[:user] = nil

And each operation I want to track I invoke:

with_user(current_user) do

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?
    Thread.current[:user] =

      Thread.current[:user] = nil

Code inside ensure will be executed each time – both when exception was raised and when execution was clean.

ArgumentError: marshal data too short when loading session data

I was stuck for a while when application maintained by me have started to throw ArgumentError: marshal data too short errors in random places When user have encountered that problem then it was unable to use application at all.


Marshal CC

Logs were showing that it happens when Rails was trying to create session object. Session store was in ActiveRecord and sessions table was not corrupted.

After watching that for a while it have shown that places in code were this exception was thrown were random but there was pattern. Page visited before was common in each case.

It have turned out that application was storing in session whole ActiveRecord object. Like:

 session[:some_info] = @variable

And later we were trying to use that way:

@variable = Model.find session[:some_info]

Due to Rails magic AcitiveRecord’s find when provided with AR object will return that object (of course if is the same model). Code was working well (maybe not very effectively since You should avoid storing large objects in session) until object stored that way started to grow. Application was collecting some data and amount of data stored have grown to that point that after Marshal.dump size of string was more than 64 kB. And this is default size of text field used to store session data in MySQL.

When You try to store too much data in text field in MySQL, excessive data is being truncated, so Marshal.load throws that exception.

To have that error solved is enough to store just object id in session (session[:some_info] =

Extracting fixtures

I’m still using fixtures. Shame, I know.

Why I do use them instead of Factory Girl or other solution like that? Well, fixtures can be much more closer to real data than mocks from Factory. How come, You ask? Fixtures are imaginary data exactly like mocks from other sources!

My answer is: that depends how You create fixtures. If You create them by hand, indeed they are disconnected from real world (like all mocks).

What is Your real data/mocks ratio?

What is Your real data/mocks ratio? CC by hsing

But I prefer to extract fixtures from real (production) database. That way I can easily pick entries created by users which are edge cases. The only trouble is with creating fixtures. For some time I’m using modified extract_fixtures rake task. I have added some conditions to extracting process – SQL condition to select only particular records and adjusted syntax to recent rake.

This is useful especially when You are about to take over application code which has no tests. Extracting real data is quick way to start write integration tests (in such case they have are most efficient – time invested and application code coverage).

How to extract fixtures without pain?

Continue reading

Testing binary downloads with Webrat

I’m using Webrat to keep some sanity when approaching maintenance of new application. Customers often come to me with legacy code, which somehow is not covered by tests.

In such case integration tests are way to go, since they provide most bang of Yours bucks – each written test could cover many parts of application.

I had to create test for testing download some data in CSV format (have You said binary? :) ). With default matchers from Webrat You won’t be able to write effective assertions – and that why I’m referring to such file as binary.


So how to do it? Here is a quick tip

Use Webrat’s response_body to get raw body returned by application. Like that:

click_link "Get me some CSV data"
ret = CSV.parse response_body
  "In third row and sixth column You should have 2 and there is #{ret[2][5]}"