简体   繁体   English

如果 gsub 的替换值为 null,我该如何设置默认值?

[英]How can I have a default in case the substituted value for gsub is null?

I currently have this as one of many in a long string of gsubs:我目前将其作为一长串 gsub 中的一个:

gsub("{Company}", contact.company_name.clear_company.to_s).

But sometimes contact.company_name is null.但有时 contact.company_name 是 null。

So I broke out from the long string something like this:所以我从长字符串中爆发出来是这样的:

subject.gsub("{Company}", contact.company_name.clear_company.to_s) unless contact.company_name.blank?

But this looks ugly and cumbersome.但这看起来又丑又麻烦。 Because here is what the entire string looks like, each one could be potentially nil which would throw an error:因为这是整个字符串的样子,所以每个字符串都可能为 nil,这会引发错误:

12     sub_message =
 13       message.gsub("{FirstName}", contact.first_name).
 14            gsub("{LastName}", contact.last_name).
 15            gsub("{Title}", contact.title || "blank").
 16        #    gsub("{Company}", contact.company_name.clear_company).
 17            gsub("{Colleagues}", colleagues.to_sentence).
 18            gsub("{NextWeek}", next_week.strftime("%A, %B %d")).
 19            gsub("{FollowingWeek}", (Date.today + 14.days).strftime("%A, %B %d")).
 20            gsub("{UserFirstName}", contact.user.first_name).
 21            gsub("{UserLastName}", contact.user.last_name).
 22            gsub("{City}", contact.address.city.titleize || "default city").
 23            gsub("{State}", contact.address.state || "default state").
 24            gsub("{Zip}", contact.address.zip || "default zip" ).
 25            gsub("{Street1}", contact.address.street1.titleize || "default street").
 26            gsub("{Today}", (Date.today).strftime("%A, %B %d")).
 27            gsub("{CustomField1}", contact.custom_field_1.to_s).
 28            gsub("{PageBreak}", "p{page-break-after: always}. ")

I'd like to do something like this我想做这样的事情

gsub("{Company}", contact.company_name.clear_company.to_s || "").

But it doesn't seem to work.但这似乎不起作用。 Ideas?想法?

The cleanest way is to use the string templating feature of Ruby 1.9.2 and you can avoid the gsub altogether.最干净的方法是使用 Ruby 1.9.2 的字符串模板功能,您可以完全避免使用 gsub。

"%{company}" % {:company => contact.company_name.clear_company || ""}

The reason this doesn't work is because you are casting it to a String.这不起作用的原因是因为您将其转换为字符串。 Even if it is nil you are essentially then calling nil.to_s which will return "" (a blank string) and the ||即使它是 nil 你基本上然后调用nil.to_s这将返回"" (一个空白字符串)和|| operator is rendered useless.运算符变得无用。

ruby-1.9.2-p136 :004 > "" || 1
 => "" 
ruby-1.9.2-p136 :005 > nil.to_s || 1
 => "" 

Now of course if your default substituted value does happen to be a blank string then this should work fine.当然,如果您的默认替换值确实是一个空白字符串,那么这应该可以正常工作。

I would write a function to use as the second argument in your gsub call.我会写一个 function 作为gsub调用中的第二个参数。

def d(s)
  s.blank? ? $DEFAULT : s
end

# Call it like this,
$DEFAULT = "default_sub"
gsub("{Company}", d contact.company_name.clear_company)

I'm retaining my other answer, because it's a straightforward answer for 1.9.2.我保留了我的另一个答案,因为它是 1.9.2 的直接答案。

In your case, I'd separate the replacements from the replacement method, which you can put in a helper to keep your views clean.在您的情况下,我会将替换方法与替换方法分开,您可以将其放入帮助程序以保持视图清洁。

The replacements can be set up in a hash:可以在 hash 中设置替换:

replacements = {
  "{Company}" => contact.company_name.clear_company || "",
  "{FirstName}" => contact.first_name,
  "{LastName}" => contact.last_name,
  "{Title}" => contact.title || "blank",
}

Then the helper method would look something like this:然后辅助方法看起来像这样:

def replace(string, replacements = {})
  replacements.each do |k,v|
    string.gsub!(k,v)
  end
  string
end

And to use it you'd just do the following:要使用它,您只需执行以下操作:

<%= replace("message", replacements) %>

Another advantage of this strategy is that when you upgrade to 1.9.2, the replacements are close to the form that can be used by the string templating feature.此策略的另一个优点是,当您升级到 1.9.2 时,替换接近字符串模板功能可以使用的形式。

If your needs are any more complex than what you've posted, I'd consider using the liquid templating engine to process your replacements.如果您的需求比您发布的更复杂,我会考虑使用液体模板引擎来处理您的替换。

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

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