At my company, Pharos, we're about to
launch a new product which will contain sensitive data for multiple
firms in a single database. This is essentially a lightweight version
of our flagship product, which was built for a single client.

Of course, as a result, I had to refactor like crazy to get rid of the
implicit "one-firm" assumption that was built into the code and database
schemas.

The essential task was to add "firm_id" to each of the private table
schemas, and then make sure that all the code that accesses the model
specifies the firm in the query. The two access idioms that were being
widely used (unsurprisingly):

results = ClassName.find(:all, :conditions => [....])

and

results = ClassName.find_by_entity_id_and_hour(...)

I was able to make minimal changes to the code by supporting the
following new idioms through a mixin (the mixin code is at the end of
the article):

(The second idiom I found easier to make (and the diff easier to read) than:

ClassName.find_by_firm_id_and_entity_id_and_hour(firm_id, ...)

but really, that's a matter of taste.)

But I was still nervous. What if I missed an instance of a database
lookup that wasn't specifying firm, and as a result one client saw
another client's records? That would be a Really Bad Thing
TM, and I want to explicitly make sure that can't
happen. But how?

After a half hour of poking around and futzing, I came up with a
find()-and-friends implementation that will check with_scope
conditions as well as the :conditions parameter to the find() call: