In a Rails app I have four models, D has one C; C belongs to B; B belongs to A. In a view template for D, we present a number of attributes off A. A typical line of code in from that template looked like
<%= @d_instance.c.b.a.attribute %>
Later, after Sandi Metz’ Four Rules dropped, we tidied things up a bit and wrapped our instance of D up in a presenter class and ended up creating methods on the presenter like
class DPresenter def attribute c.b.a.attribute end end
to approximate a Facade pattern.
This cleaned up the view, which now had expressions like
<%= d_instance_presenter.attribute %> (ta-da! rule four!). Some time after that, “Ruby Science” introduced me to Law of Demeter. I now look at what I did with that presenter and think I need to reconsider my approach.
Given that I need to present a half dozen attributes off A on this view, with the potential for more in the future, what can I do? Do I simply end up creating accessor methods on D that delegate to C for each model attribute I need off of A? Is there another way?
What about naming those methods? Let’s say I decide to put a new method on D that requests
attribute from its neighbor, C, which, in turn, delegates all the way to A for the real value. Is there a generally accepted way to name those methods? I fear that a straightforward
d.attribute will run in to namespace collisions down the road, so I am inclined to name it
d.a_attribute, but that feels a little cheesy.
Relatedly, what do you all think of Rails’
has_one :through? If you squint really hard, it’s kinda-sorta addressing LoD. Do devs who try to follow LoD use it?