2010-09-02 21 views
11

我经常编写代码以在遇到nil /空值时提供默认值。在默认值替换习语中,是否在内建的rails支持中?

E.g:

category = order.category || "Any" 
# OR 
category = order.category.empty? ? "Any" : order.category 

我将延长try方法来处理这个成语。

category = order.try(:category, :on_nill => "Any") 
# OR 
category = order.try(:category, :on_empty=> "Any") 

我想知道如果Rails/Ruby有一些方法来处理这个习惯用法?

注:

我试图消除||/or/?运营商基于成语重复。

本质上,我正在寻找一个等效的try方法来处理默认的替代方案。

没有try方法:

product_id = user.orders.first.product_id unless user.orders.first.nil? 

随着try方法:

product_id = user.orders.first.try(:product_id) 

这是很容易实现一个通用的方法来处理这个成语,但我要确保我不重新发明轮。

回答

12

this question。如果present?(与blank?相反)和nil,ActiveSupport将presence方法添加到返回接收方的所有对象。

实施例:

host = config[:host].presence || 'localhost' 
+0

超酷的答案! – kamal 2016-08-08 04:08:40

1

或许这可能有助于:

class Object 
    def subst_if(condition, replacement) 
    condition = send(condition) if condition.respond_to?(:to_sym) 
    if condition 
     replacement 
    else 
     self 
    end 
    end 
end 

使用像这样:

p ''.subst_if(:empty?, 'empty')  # => "empty" 
p 'foo'.subst_if(:empty?, 'empty') # => "foo" 

它也需要独立的条件下,没有相关的对象:

p 'foo'.subst_if(false, 'bar') # => 'foo' 
p 'bar'.subst_if(true, 'bar') # => 'bar' 

我对于名字subst_if并不疯狂。如果我知道它(假设它存在),我会借用Lisp用于此函数的任何名称。

+0

1,这是一个有趣的方法。我正在考虑扩展'try'方法,因为我已经在很多地方使用它了。 – 2010-09-03 00:03:59

0

很确定它没有烤出来。这是一个链接到similar question/answer。这是我采取的方法。凭借红宝石:||=语法

旁白:这个问题也让我想起了所有的时间第一Railscasts的:Caching with instance variables这是一个有用的截屏,如果你需要做这样的操作在控制器