Thursday, October 8, 2009

Named instances for ActiveRecord

For a project that I'm working on at my day job, we have a governmental client for which we are building a pretty large and complicated online/offline Ruby on Rails application. As part of this app there are tons of data-specific rules. For example, if a client with HIV is being assessed then certain fields may have to be displayed/hidden and there are rules that get applied differently. So lets say you have the following setup:

http://gist.github.com/205241

Now, somewhere in your code you want to be able to do take a specific action only if that client has a particular diagnosis. Without named_instances you might do something like:

http://gist.github.com/205250

With named_instances you can do the following faster and more concise code:

http://gist.github.com/205253

We've been using this functionality for about 6 months now and its been great. The gem is out on GemCutter (which rocks) and the repo is at GitHub. Hopefully it will be useful in your projects. Comments, criticisms, and patches welcome.