Archive for August 2016
Specialist: A pattern for carving up fat ActiveRecord models
All roads to a well-factored Rails application lead from fat controllers through fat models. Where to head next is less well mapped. Many patterns move non-model code into separate layers. When you’ve gone down that path as far as you can, your models can still be weighed down with code that would belong in a model — if there weren’t so much of it. Specialist is a pattern that makes it surprisingly easy to slice up your fat models into lean modules.
Using and testing automatic accessors and virtual attributes of ActiveRecord models
An ordinary ActiveRecord model object has an attribute for each column in its table. Each attribute has a reader method and a writer method. However, ActiveRecord also defines accessors on the fly to hold non-column query results. Also, sometimes it’s useful to define a new attribute, one not corresponding to a column or even to a field in a query result. These different kinds of extra attributes can interfere with one another, making them tricky to use and test. The best defense is to understand all of them well before using any of them. Let’s have a look.