0

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

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

但是一旦我尝试创建我的 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'
4

2 回答 2

0

内部BitBucket.new do..end块,self设置为config. 但current_user不是BitBucket类的实例方法。因此抛出一个有效的错误。

于 2013-11-07T11:41:33.570 回答
0

似乎传递给的块是在新实例BitBucket.new的上下文中执行的(真的,根据this)。BitBucket::ClientBitBucket.newBitBucket::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
于 2013-11-07T11:41:46.350 回答