[英]How to chain try() and scoped to_s() in Rails?
In a Rails view, one can use try
to output only if there is a value in the database, eg 在Rails视图中,只有在数据库中存在值时才可以使用
try
输出,例如
@model.try(:date)
And one can chain trys if, for example, the output is needed as a string 例如,如果输出需要作为字符串,则可以链接trys
@model.try(:date).try(:to_s)
But what if I need to call a scoped format? 但是如果我需要调用范围格式呢? I've tried
我试过了
@model.try(:date).try(:to_s(:long))
@model.try(:date).try(:to_s).try(:long)
What is the correct syntax for this? 这个的正确语法是什么? And what is a good reference for more explanation?
什么是更好解释的好参考?
Thanks 谢谢
From the fine manual : 从精细手册 :
try(*a, &b)
试试(* a,&b)
[...][...]
try
also accepts arguments and/or a block, for the method it is tryingtry
也接受参数和/或块,对于它正在尝试的方法Person.try(:find, 1)
So I think you want: 所以我想你想要:
@model.try(:date).try(:to_s, :long)
This one won't work: 这个不起作用:
@model.try(:date).try(:to_s(:long))
because you're trying to access the :to_s
symbol as a method ( :to_s(:long)
). 因为您尝试访问
:to_s
符号作为方法( :to_s(:long)
)。 This one won't work: 这个不起作用:
@model.try(:date).try(:to_s).try(:long)
because you're trying to call the long
method on what to_s
returns and you probably don't have a String#long
method defined. 因为你试图在什么
to_s
返回上调用long
方法,你可能没有定义String#long
to_s
方法。
mu is too short's answer shows the correct usage for the try
method with parameters: mu太短了答案显示了带参数的
try
方法的正确用法:
@model.try(:date).try(:to_s, :long)
However, if you are using Ruby 2.3 or later, you should stop using try
and give the safe navigation operator a try (no pun intended): 但是,如果您使用的是Ruby 2.3或更高版本,则应该停止使用
try
并try
安全导航操作符(无双关语):
@model&.date&.to_s(:long)
The following answer is here for historical purposes – adding a rescue nil
to the end of statements is considered bad practice, since it suppresses all exceptions: 以下答案出于历史目的 - 在语句末尾添加一个
rescue nil
被认为是不好的做法,因为它会抑制所有异常:
For long chains that can fail, I'd rather use:
对于可能失败的长链,我宁愿使用:
@model.date.to_s(:long) rescue nil
Instead of filling up my view with
try(...)
calls.而不是使用
try(...)
调用填充我的视图。Also, try to use
I18n.localize
for date formatting, like this:另外,尝试使用
I18n.localize
进行日期格式化,如下所示:l @model.date, format: :long rescue nil
See: http://rails-bestpractices.com/posts/42-use-i18n-localize-for-date-time-formating
请参阅: http : //rails-bestpractices.com/posts/42-use-i18n-localize-for-date-time-formating
In case you often use try chains without blocks, an option is to extend the Object class: 如果您经常使用不带块的try链,则可以选择扩展Object类:
class Object
def try_chain(*args)
args.inject(self) do |result, method|
result.try(method)
end
end
end
And then simply use @model.try_chain(:date, :to_s)
然后只需使用
@model.try_chain(:date, :to_s)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.