问题
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
回答1:
To be honest, slavish adherence to the Law of Demeter is pretty rare. Still, for associations, this is such a common pattern that it has a shortcut that removes most of the hard work from you:
class PeriodRegistration < ActiveRecord::Base
belongs_to :period
delegate :event, :to => :period
end
PeriodRegistration.new.event # calls PeriodRegistration.new.period.event
You can read more about this at the Module#delegate documentation.
At the risk of sounding excessively self-promoting, I have a blog post that discusses this and other ways to try to respect the Law of Demeter, if that's your thing. Check it out if you're curious to learn more.
来源:https://stackoverflow.com/questions/12237431/the-law-of-demeter