2014-09-20 78 views
0

我在表中有一列其值和CSS类根据布尔值而不同。最初的版本我是:将函数的返回值分配给块的参数

%td.sba{ class: product.sold_by_amazon? ? :yes : :no }= product.sold_by_amazon? ? '✔' : '–' 

我想删除重复布尔查询,并结束了:

- Proc.new{ |p| yield ([{ yes: :✔ }, { no: :– }].try(:[], product.sold_by_amazon? ? 0 : 1)) }.call do |sold, text| 
    %td.sba{ class: sold }= text 

有一个不太令人费解的方式做到这一点?

此外,更简单的解决方案是使用CSS content生成文本。

+1

代码视图通常是一个X/Y问题的气味的结果。为什么这不是作为模型中的虚拟属性处理的? – 2014-09-20 02:46:54

回答

0

你可以只移动这个逻辑来帮手,写类似:

def sold_by_amazon_row(product) 
    if product.sold_by_amazon? 
    content_tag :td, '✔', class: "sba yes" 
    else 
    content_tag :td, '-', class: "sba no" 
    end 
end 

然后:

= sold_by_amazon_row(product) 



当然你可以添加这个方法原始类如:

class TrueClass 
    def yes_no 
    "Yes" 
    end 

    def sign 
    "+" 
    end 
end 

class FalseClass 
    def yes_no 
    "No" 
    end 

    def sign 
    "-" 
    end 
end 

或使用猴子修补和写类似:

class << bool 
    def yes_no 
    self ? "Yes" : "No" 
    end 

    def sign 
    self ? "+" : "-" 
    end 
end 

,但你不应该让大象出苍蝇的,也正如我opition即使使用简单的?:看起来更清晰比:

Proc.new{ |p| yield ([{ yes: :✔ }, { no: :– }].try(:[], product.sold_by_amazon? ? 0 : 1)) }.call do |sold, text| 
0

为什么你关心“重复的布尔查找”?

如果它是一个效率的东西,那么memoize的谓词功能.sold_by_amazon?

#product.rb 
def sold_by_amazon? 
    return false if @sold_by_amazon == false 
    @sold_by_amazon || = calculate_if_sold_by_amazon 
end 

private 
def calculate_if_sold_by_amazon 
    # some expensive calculation to work out whether or not this is sold by Amazon 
end 
+0

你可以删除一个答案;) – IS04 2014-09-20 06:16:41

+0

grrrr ...野餐 - 它应该是一个编辑 - 结束为一个双重职位: - / – Pavling 2014-09-20 06:29:13

相关问题