如何使用ruby方法.present?

时间:2013-09-15 08:45:34

标签: ruby-on-rails ruby

我在rails app中有这样的方法:

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

之前我没有使用.present?方法,所以我进入了我的交互式ruby shell来玩它。

每当我使用xxx.present?时,它都会返回NoMethodError。如果xxx是字符串,数字,数组,则无关紧要。

我该如何使用这种方法?

3 个答案:

答案 0 :(得分:20)

presentActiveSupport提供的方法。它不是核心红宝石的一部分。这就是为什么你不能在红宝石外壳中使用它。要使用它,您需要在控制台中需要相关的库(例如irb / pry):

require 'active_support'
require 'active_support/core_ext'

这样,您就可以访问activesupport提供的所有实用工具方法。

答案 1 :(得分:6)

present是一种rails方法,而不是ruby 尝试使用rails c代替irb在您的控制台中使用它。

答案 2 :(得分:3)

如上所述,.present不在ruby标准库中。相反,它位于active_support(docs。)

要使用active_support,请首先安装gem,然后在irb或ruby脚本中使用它。有关如何有选择地加载activesupport扩展的更多信息,请参阅Rails guides