简体   繁体   English

如何使这些“ if”语句更干燥?

[英]How can I make these “if” statements more DRY?

I'm trying to layout some partials as shown below: 我正在尝试布局一些局部,如下所示:

if controller == home
   render partail 0
else
   render partial 1
end

render partial 2

render partial 3

if controller == home
   render partail 4
end

render partial 5

I've repeated the if controller == home part three times. 我已经重复了if controller == home部分3次。 Is there any way to make the code follow the "DRY" approach? 有什么方法可以使代码遵循“ DRY”方法?

You could use an array: 您可以使用数组:

partials = (controller == home) ? [0,2,3,4,5] : [1,2,3,5]

partials.each { |p| render partial p }

Here's how I might do it. 这就是我可能会做的。 It's not any more DRY, but it reads better, IMO: IMO,它不再是DRY,但它读起来更好。

flag = controller == home

render flag ? :partial0 : :partial1
render :partial2
render :partial3
render :partial4 if flag
render :partial5

You can use an array and since the partials are ordered, sort it, then render: 您可以使用数组,并且由于部分是有序的,因此请对其进行排序,然后进行渲染:

partials = [2,3,5];                     # 2,3,5 are going to be rendered regardless of controller

case controller
when home
   partials.push(0,4);                  # if it's home use 0 and 4
else
   partials.push(1);                    # if not home use 1
end

partials.sort.each { |p| render partial p }  # sort and render in order

Note: there is more code in this example, but it is more flexible if you expect to use other conditionals in addition to home . 注意:此示例中包含更多代码,但是如果您希望除了home之外还使用其他条件,则它将更加灵活。 I often find the more robust I make my code up front, it saves me more time in the long run; 我经常发现我使代码更健壮,从长远来看,它可以节省更多时间; though, I admit this is less readable as compared to FMc 's answer 不过,我承认,与FMc的答案相比, 的可读性较差

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM