2010-11-23 78 views
1
unless @client.nil? 
    TestMailer.snap_shot_error("test1","Errors", 
     {:file_name => File.basename(upload_file),:client_name => @client.client_name}) 
else 
    TestMailer.snap_shot_error("test1","Errors", 
     {:file_name => File.basename(upload_file)) 
end 

def snap_shot_error(to_address,subject,options={}) 
    # code 
end 

<% if @client_name %> 
    <%= _("There were problems with file ") + @file_name + _(" for client ") + @client_name %> 
<% else %> 
    <%= _("There were problems with file ") + @file_name %> 
<% end %> 

回答

3

对于这两个问题,您可以使用三元运算符。它的工作原理是这样的

condition ? value_if_true : value_if_false 

这是一个表达式(产生另一个值的值和运算符序列)。它确定条件是真还是假,并且如果条件为真,则评估为第一值(在?之后和之前);如果条件为真,则评估为第二值(在:)之后)。

那么,对于您发布的第一个代码示例,你可以这样做:

TestMailer.snap_shot_error("test1", "Errors", 
    :file_name => File.basename(upload_file), 
    :client_name => @client ? @client.client_name : nil) 

[注意我已经删除花括号周围的选项 - 在Ruby中有没有需要,在最终选择乱码,这是惯用离开他们关闭]

或者,如果由于某种原因,你甚至不想要一个零:CLIENT_NAME在哈希,您可以使用三元运算和合并:

TestMailer.snap_shot_error("test1", "Errors", 
    {:file_name => File.basename(upload_file)}.merge(
    @client ? { :client_name => @client.client_name } : {})) 

对于视图,您还可以使用三元运算:

<%= _("There were problems with file ") + @file_name + 
    (@client_name ? _(" for client ") + @client_name : '') %> 

而现在,我看你是用@client_name做什么,我不明白为什么你说你需要,它甚至不会在哈希值。我发布的第一个代码示例中,如果有客户端,并且在没有客户端的情况下传递“:client_name => nil”,则它传递“:client_name => @ client.client_name”,应该可以正常工作。没有理由不传递:client_name,而不是传递一个nil:client_name。

+0

我不想在选项中传递client_name键。如果@client不可用。 – 2010-11-23 18:52:32