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