我创建了一个包装类 rclient 来使用 Excon 进行 http 调用。在我的控制器类中,我实例化并调用该类上的一个方法。在调试时,我注意到在客户端类 @client 变量的 post 方法中始终为零。
我更改了代码(参见方法 2),使用 Excon 的新实例实例化一个 @cient 变量并在同一方法中使用该变量,然后它不为空。我不确定为什么首先在方法中,我可以访问在 initialize 方法中设置的 @client 变量。有任何想法吗?
方法一
module API
class rclient
def initialize
@client ||= Excon.new('http://example.com')
end
def post
#error @client is nil
post_response = @client.Post(path:'/create', body:{date:'somedata'});
end
end
end
class my controller < ApplicationController
def create
req = API::rclient.new()
req.post
end
end
方法二
module API
class rclient
def post
@client = Excon.new('http://example.com')
post_response = @client.Post(path:'/create', body:{date:'somedata'});
end
end
end
class my controller < ApplicationController
def create
req = API::rclient.new()
req.post
end
end
@client
变量将被初始化为两个变体。对于所描述的场景,此代码“改编”中可能缺少 smth。这是您可以检查的稍微调整的演示代码:
# app.rb
require 'rubygems'
require 'bundler/setup'
Bundler.require(:default)
module API
class Rclient
def initialize
@client ||= Excon.new('http://example.com')
end
def post
post_response = @client.post(path:'/create', body: URI.encode_www_form(date: 'somedata'))
end
end
class Rclient2
def post
@client = Excon.new('http://example.com')
post_response = @client.post(path:'/create', body: URI.encode_www_form(date: 'somedata'))
end
end
end
req1 = API::Rclient.new
req2 = API::Rclient2.new
req1.post
req2.post
raise 'First implementation failed' unless req1.instance_variable_get(:@client).is_a?(Excon::Connection)
raise 'Second implementation failed' unless req2.instance_variable_get(:@client).is_a?(Excon::Connection)
# Gemfile
source 'https://rubygems.org'
git_source(:github) { |repo| "https://github.com/#{repo}.git" }
ruby '2.6.5'
gem 'excon'
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句