如果 gsub 的替换值为空,我怎样才能有默认值?

发布于 2024-11-14 11:03:42 字数 1644 浏览 6 评论 0原文

我目前将其作为一长串 gsub 中的众多之一:

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

但有时 contact.company_name 为 null。

所以我从长绳子中爆发出这样的东西:

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

但这看起来又丑又麻烦。因为这是整个字符串的样子,所以每个字符串都可能为零,这会引发错误:

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}. ")

我想做这样的事情,

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

但它似乎不起作用。有想法吗?

I currently have this as one of many in a long string of gsubs:

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

But sometimes contact.company_name is 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:

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

贵在坚持 2024-11-21 11:03:42

最干净的方法是使用 Ruby 1.9.2 的字符串模板功能,您可以完全避免使用 gsub。

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

The cleanest way is to use the string templating feature of Ruby 1.9.2 and you can avoid the gsub altogether.

"%{company}" % {:company => contact.company_name.clear_company || ""}
野味少女 2024-11-21 11:03:42

我保留我的另一个答案,因为这是 1.9.2 的简单答案。

就您而言,我会将替换方法与替换方法分开,您可以将其放入助手中以保持视图干净。

可以在散列中设置替换:

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

然后辅助方法将如下所示:

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

要使用它,您只需执行以下操作:

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

此策略的另一个优点是,当您升级到 1.9.2 时,替换为接近字符串模板功能可以使用的形式。

如果您的需求比您发布的内容更复杂,我会考虑使用 liquid 模板引擎处理您的替代品。

I'm retaining my other answer, because it's a straightforward answer for 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:

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.

If your needs are any more complex than what you've posted, I'd consider using the liquid templating engine to process your replacements.

我不在是我 2024-11-21 11:03:42

这不起作用的原因是因为您将其转换为字符串。即使它是 nil,你本质上也是在调用 nil.to_s ,它将返回 "" (一个空白字符串),而 || 运算符是变得无用。

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

当然,如果您的默认替换值恰好是空白字符串,那么这应该可以正常工作。

我会编写一个函数用作 gsub 调用中的第二个参数。

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

# Call it like this,
$DEFAULT = "default_sub"
gsub("{Company}", d 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 || 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.

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

# Call it like this,
$DEFAULT = "default_sub"
gsub("{Company}", d contact.company_name.clear_company)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文