简体   繁体   English

如何使用ruby方法.present?

[英]How to use ruby method .present?

I have a method like this in rails app: 我在rails app中有这样的方法:

def current_user
        return @current_user if @current_user.present?
        @current_user = current_user_session && current_user_session.record
end

I haven't used the .present? 我没有用过.present? method before so I went into my interactive ruby shell to play around with it. 之前的方法,所以我进入我的交互式红宝石外壳玩它。

Whenever I use xxx.present? 每当我使用xxx.present? it returns a NoMethodError. 它返回NoMethodError。 It doesn't matter if xxx is a string, number, array anything. 如果xxx是字符串,数字,数组,则无关紧要。

How can I use this method? 我该如何使用这种方法?

present is a method provided by ActiveSupport . presentActiveSupport提供的方法。 It is not a part of core ruby. 它不是核心红宝石的一部分。 That is why you are not able to use it in the ruby shell. 这就是为什么你不能在红宝石外壳中使用它。 To play around with it, you will need to require the relevant libraries in your console (eg irb / pry): 要使用它,您需要在控制台中需要相关的库(例如irb / pry):

require 'active_support'
require 'active_support/core_ext'

This way, you will have access to all the utility methods provided by activesupport . 这样,您就可以访问activesupport提供的所有实用程序方法。

present is a rails method, not ruby. 目前是铁路方法,而不是红宝石。
try using rails c instead of irb to use it in your console. 尝试使用rails c而不是irb在您的控制台中使用它。

As mentioned above, .present is not in the ruby standard library. 如上所述, .present不在ruby标准库中。 Instead, it's in active_support ( docs .) 相反,它在active_support( docs 。)中

To use active_support, first install the gem, then require it in irb or your ruby script. 要使用active_support,首先安装gem,然后在irb或ruby脚本中使用它。 More information on how to selectively load activesupport extensions can be found in the Rails guides . 有关如何有选择地加载activesupport扩展的更多信息,请参阅Rails指南

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

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