我如何将得墨忒耳定律应用于此? [英] How do I apply the Law of Demeter to this?

查看:87
本文介绍了我如何将得墨忒耳定律应用于此?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个公认的丑陋查询要做,以查找与当前角色相关的特定角色.这一行产生了正确的结果:

I have an admittedly ugly query to do, to find a particular role related to the current role. This line produces the correct result:

@person_event_role.event_role.event.event_roles.
  joins(:mission_role).where(:mission_roles => {:title => 'Boss'}).
  first.person_event_roles.first.person

(您可以从多个调用中推断出关联)

(You can infer the associations from the plurality of those calls)

获取此信息的唯一方法需要大量的数据库结构知识,但要消除耦合...需要在该链的每个步骤中填写一堆辅助函数以返回需要的信息...

The only way to get this information requires a ton of knowledge of the structure of the database, but to remove the coupling... It would require filling in a bunch of helper functions in each step of that chain to give back the needed info...

推荐答案

我认为这里要做的是在适当的地方创建辅助函数.我不清楚你的关联链的开头是什么,但我可能会为它分配一个方法 #event 返回 event_role.event.从那里,一个 event 有一个 #boss_role,或者任何在语义上有意义的东西,那个方法是

I think the thing to do here is to create the helper functions where appropriate. I'm unclear what the beginning of your association chain is here, but I'd probably assign it a method #event that returns event_role.event. From there, an event has an #boss_role, or whatever makes sense semantically, and that method is

event_roles.joins(:mission_role).where(:mission_roles => {:title => 'Boss'}).first 

最后,同样在 Event 模型上,有一个 #boss 方法,它得到

Finally, also on the Event model, there's a #boss method, which gets

boss_roles.first.person_event_roles.first.person

因此,您的原始查询变为

So, your original query becomes

@person_event_role.event.boss

链条的每条腿都是独立的并且易于理解,并且不需要链条的开头就知道它的结尾.我不完全理解这些关联的全部范围,但我很确定只需将其分解为三个或四个模型方法,您就可以清楚地阅读和分离您正在寻找的关注点.您甚至可以将其进一步分解以方便阅读,但这变成了风格问题.

Each leg of the chain is then self-contained and easy to understand, and it doesn't require the beginning of your chain to be omniscient about the end of it. I don't fully comprehend the full reach of these associations, but I'm pretty sure that just breaking it into three or four model methods will give you the clean reading and separation of concerns you're looking for. You might even break it down further for additional ease of reading, but that becomes a question of style.

希望有帮助!

以下是原发问者

我想我遵循了这个建议,结果是:

I think I followed this advice and ended up with:

@person_event_role.get_related_event_roles_for('Boss').first.filled_by.first

#person_event_role:
def get_related_event_roles_for(role)
  event.event_roles_for(role)
end

def event
 event_role.event
end

#event:
def event_roles_for(role)
  event_roles.for_role(role)
end

#event_role:
scope :for_role, lambda {|role| joins(:mission_role).where(:mission_roles => {:title => role})}
def filled_by
  person_event_roles.collect {|per| per.person}
end

这篇关于我如何将得墨忒耳定律应用于此?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆