无法访问应用程序控制器中 .new do 块中的current_user



我正在使用 devise 和 bitbucket api gem,我的 ApplicationController 中有一个方法可以创建一个实例,以便我可以进行 API 调用。为此,它会尝试从current_user读取令牌和机密。

这适用于硬编码的令牌和秘密字符串,我也能够在 do 块之前执行puts current_user.inspect,并且一切正常。我也确信bb_token和bb_secret存在(我可以单独调用它们)。

但是一旦我尝试创建我的 bitbucket 实例,它就无法再读取current_user。有什么想法吗?

class ApplicationController < ActionController::Base
  protect_from_forgery
  helper_method :current_user
  def bitbucket
    puts "token----------"
    puts current_user
    @bitbucket = BitBucket.new do |config|
      config.oauth_token   = current_user.bb_token # replaceing this with hardcoded string works
      config.oauth_secret  = current_user.bb_secret # replaceing this with hardcoded string works
      config.client_id     = 'xx'
      config.client_secret = 'yy'
      config.adapter       = :net_http
    end
  end
end

和错误:

NameError (undefined local variable or method `current_user' for #<BitBucket::Client:0x007fbebc92f540>):
  app/controllers/application_controller.rb:12:in `block in bitbucket'
  app/controllers/application_controller.rb:11:in `bitbucket'
似乎

传递给BitBucket.new的块是在新的BitBucket::Client实例的上下文中执行的(BitBucket.new确实是BitBucket::Client.new,根据这个)。

一眼消息来源证实了这一假设。

如果要传递current_user,可以回想一下块是闭包,因此它们保留了定义它们的上下文。所以你可以做这样的事情:

def bitbucket
  # (...)
  user = current_user # local variable assignment
  @bitbucket = BitBucket.new do |config|
    config.oauth_token = user.bb_token # it works because user is local variable and the block is closure
    # (...)
  end
end

在块BitBucket.new do..end内,self设置为 config 。但current_user不是BitBucket类的实例方法。因此,将引发有效错误。

相关内容

最新更新