无法访问ApplicationController中的.new do block中的current_user

时间:2013-11-07 11:37:42

标签: ruby ruby-on-rails-3 devise

我正在使用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'

2 个答案:

答案 0 :(得分:0)

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

答案 1 :(得分:0)

根据this,似乎传递给BitBucket.new的块是在新BitBucket::Client实例的上下文中执行的(BitBucket.new确实是BitBucket::Client.new

source的一瞥证实了这一假设。

如果要传递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