2

I recently posted a question on stackoverflow where I did something to effect of

@period_registration.period.event

However, it was suggested that I do something like the following:

def event
  period.event
end

@period_registration.event

My general sense is that this seems a little heavy-handed. Looking at this previous posting How do I apply the Law of Demeter to this? shows how heavy handed this can become if you did this for every association.

How common of a practice is this in rails? My thought is that even if this is technically the right thing to do, if it isn't a part of the rails culture then it seems that doing this will throw people off. And, more importantly, actually make the code less maintainable as other developers think you're wasting your time with all these helper methods.

Let's say I wanted to impliment this, would @period_registration.event.city, where city is an attribute of event, not a seperate object also violate LoD or would I need to write ANOTHER method so I could do: @period_registration.city

4

1 回答 1

5

老实说,盲目地遵守得墨忒耳法则是非常罕见的。尽管如此,对于关联来说,这是一种常见的模式,它有一个快捷方式可以消除您的大部分辛勤工作:

class PeriodRegistration < ActiveRecord::Base
  belongs_to :period
  delegate :event, :to => :period
end

PeriodRegistration.new.event # calls PeriodRegistration.new.period.event

您可以在Module#delegate文档中阅读更多相关信息。

冒着听起来过度自我推销的风险,我有一篇博客文章讨论了这个和其他尝试尊重德墨忒耳法则的方法,如果那是你的事。如果您想了解更多信息,请查看它。

于 2012-09-02T16:14:48.497 回答