2013-05-13 47 views
-5

有没有办法让这个Rails代码漂亮起来?如何清理这个非常简单的Rails函数?

def function 
    if new_record?      
    thing 
    else 
    thing + yet_another_thing 
    end 
end 

我不喜欢的thing重复这里,所以我不知道是否有一个更清洁的方式。

感谢您的任何帮助。

+6

什么是类'thing'? – sawa 2013-05-13 21:37:38

+1

非常通用...... – Mindbreaker 2013-05-13 21:53:07

+0

Ehm ...可能有thing.class调用的输出吗? – byterussian 2013-05-13 21:57:32

回答

3

这适用于支持+任何对象, (甚至是字符串。)

[thing, (yet_another_thing unless new_record?)].compact.inject(:+) 

它干燥而可怕,就像被困在没有水的沙漠中一样。


您可能还能够与闪避:

thing.dup.tap{|t| t << yet_another_thing unless new_record?} 

如果事情是一个整数这是不行的(你不能DUP它),也需要支持< <运营商。

也干,但以不同的方式吓人。

+0

同样的模式工作正常字符串:只需更换'注入(:+)'和'join' – 2013-05-13 22:11:57

+1

的注射用绳子工作为好。 – 2013-05-13 22:13:04

0

如果你不想重复thing,那么这可能是一个解决方案。

def function 
    result = thing 
    result += yet_another_thing unless new_record? 
    result 
end 
+1

你重复三次'result'而不是重复'thing'两次。我认为这没有帮助。 – sawa 2013-05-13 21:46:49

+0

如果_thing_是一个不平凡的表达式或函数调用,那么它是一个有用的模式。 – 2013-05-13 22:09:14

0

你可以使用一个在线如果

def function 
    return thing if new_record? 
    thing + yet_another_thing 
end 
0

如果thingyet_another_thing是字符串,你可以这样做:

thing + (yet_another_thing unless new_record?).to_s 
+0

他们不是:-( – Tintin81 2013-05-13 21:54:21

+4

串那么,什么是他们 – tessi 2013-05-13 21:54:55

1

三元算子呢?

def function 
    new_record? ? thing : (thing + yet_another_thing) 
end 

如果我们知道你在哪里使用它或者包含在变量中,这将会更有帮助。

0

如果事情和yet_another_thing一些方法你打电话:

def function 
    thing 
    yet_another_thing if new_record? 
end