Ruby-on-rails rails 如果 object.nil?然后魔术''在意见?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/523164/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 20:57:29  来源:igfitidea点击:

rails if object.nil? then magic '' in views?

ruby-on-railsruby

提问by Jeremy

This is one of those things, that maybe so simple I'll never find it because everyone else already knows it.

这就是其中之一,也许如此简单我永远找不到它,因为其他人都已经知道了。

I've got objects I have to check for nil in my views so I don't dereference a nil:

我有一些对象,我必须在我的视图中检查 nil,所以我不会取消引用 nil:

<%= if tax_payment.user; tax_payment.user.name; end %>

Or I could do this variant:

或者我可以做这个变体:

<%= tax_payment.user ? tax_payment.user.name : '' %>

So this is ok ... for most languages. But I feel like there must be some bit of shiny ruby or railness I'm still missing if this is the best I can do.

所以这没问题……对于大多数语言。但我觉得一定有一些闪亮的红宝石或横梁,如果这是我能做的最好的,我仍然想念。

回答by Sophie Alpert

What about:

关于什么:

<%= tax_payment.user.name if tax_payment.user %>

回答by Toby Hede

You can also try the new Object.try syntax, pardon the pun.

您还可以尝试新的 Object.try 语法,请原谅双关语。

This is in the shiny new Rails 2.3:

这是在闪亮的新 Rails 2.3 中:

tax_payment.try(:user).try(:name)

回答by Antti Tarvainen

The Ruby community has put an incredible amount of attention to automating this idiom. These are the solutions I know of:

Ruby 社区对自动化这个习语给予了极大的关注。这些是我所知道的解决方案:

The most well-known is probably the try methodin Rails. However, it has received somecriticism.

最著名的可能是Rails 中的try 方法。然而,它受到了一些批评

In any case, I think Ben's solution is perfectly sufficient.

无论如何,我认为 Ben 的解决方案是完全足够的。

回答by KenB

I've always preferred this approach:

我一直更喜欢这种方法:

model:

模型:

class TaxPayment < ActiveRecord::Base
  belongs_to :user
  delegate :name, :to=>:user, :prefix=>true, :allow_nil=>true
end

view:

看法:

<%= tax_payment.user_name %>

http://apidock.com/rails/Module/delegate

http://apidock.com/rails/Module/delegate

回答by J?rg W Mittag

For a little more comprehensive solution, you could check out the Introduce Null ObjectRefactoring. The basic mechanics of this refactoring is that instead of checking for nilin the clientcode you instead make sure that the providernever produces a nilin the first place, by introducing a context-specific null objectand returning that.

对于更全面的解决方案,您可以查看Introduce Null ObjectRefactoring。这种重构的基本机制是,通过引入特定于上下文的空对象并返回它,而不是nil客户端代码中检查,而是确保提供者从一开始就不会产生 a 。nil

So, return an empty string, an empty array, an empty hash or a special empty customer or empty user or something instead of just niland then you will never need to check for nilin the first place.

因此,返回一个空字符串、一个空数组、一个空散列或一个特殊的空客户或空用户或其他东西,而不仅仅是nil这样,您将永远不需要首先检查nil

So, in your case you would have something like

所以,在你的情况下,你会有类似的东西

class NullUser < User
    def name
        return ''
    end
end

However, in Ruby there is actually another, quite elegant, way of implementing the Introduce Null Object Refactoring: you don't actually need to introducea Null Object, because nilis alreadyan object! So, you could monkey-patch nilto behave as a NullUser?– however, all the usual warnings and pitfalls regarding monkey-patching apply even more strongly in this case, since making nilsilently swallow NoMethodErrors or something like that can totally mess up your debugging experience and make it reallyhard to track down cases where there is a nilthat shouldn't be there (as opposed to a nilthat serves as a Null Object).

然而,在 Ruby 中,实际上还有另一种非常优雅的方式来实现引入空对象重构:您实际上不需要引入空对象,因为nil已经是一个对象!那么,您可以使用猴子补丁nil来表现为 NullUser 吗? - 然而,所有关于猴子补丁的常见警告和陷阱在这种情况下更加适用,因为nil静默吞下NoMethodErrors 或类似的东西会完全弄乱您的调试体验并使其确实很难追查案件,其中有一个nil是不应该存在(而不是一个nil用作空对象)。

回答by Matt Darby

I just do

我只是做

<%= tax_payment.user.name rescue '' %>

回答by Jeremy Weiskotten

Another option, which makes sense occasionally...

另一种选择,偶尔有意义......

If tax_payment.user returns nil, nil.to_s (an empty string) is printed, which is harmless. If there is a user, it will print the user's name.

如果 tax_payment.user 返回 nil,则打印 nil.to_s(空字符串),这是无害的。如果有用户,它会打印用户名。

回答by Linus

You could write a helper method which looks like this:

您可以编写一个如下所示的辅助方法:

def print_if_present(var)
    var ? var : ""
end

And then use it like this (in the view):

然后像这样使用它(在视图中):

<%= print_if_present(your_var) %>

<%= print_if_present(your_var) %>

If the var is nil, it just prints nothing without raising an exception.

如果 var 为 nil,它只是不打印任何内容而不会引发异常。