我开发了一个应用程序,允许我们的客户创建自己的会员保护网站.然后,我的应用程序连接到外部API服务(客户特定的api_key/api_url),以同步/更新/添加数据到此其他服务.好吧,我已经为这个其他服务编写了一个API包装器.但是,我现在看到连接为零的随机丢弃.以下是我目前使用连接的方式:
我有一个xml/rpc连接类
class ApiConnection
attr_accessor :api_url, :api_key, :retry_count
def initialize(url, key)
@api_url = url
@api_key = key
@retry_count = 1
end
def api_perform(class_type, method, *args)
server = XMLRPC::Client.new3({'host' => @api_url, 'path' => "/api/xmlrpc", 'port' => 443, 'use_ssl' => true})
result = server.call("#{class_type}.#{method}", @api_key, *args)
return result
end
end
Run Code Online (Sandbox Code Playgroud)
我还有一个模块可以包含在我的模型中以访问和调用api方法
module ApiService
# Set account specific ApiConnection obj
def self.set_account_api_conn(url, key)
if ac = Thread.current[:api_conn]
ac.api_url, ac.api_key = url, key
else
Thread.current[:api_conn] = ApiConnection.new(url, key)
end
end
########################
### Email Service …Run Code Online (Sandbox Code Playgroud) 我的应用程序控制器中有以下内容:
before_filter :set_current_subdomain
protected
def set_current_subdomain
Thread.current[:current_subdomain] = current_subdomain
@account = Account.find_by_subdomain(current_subdomain)
end
def current_subdomain
request.subdomain
end
Run Code Online (Sandbox Code Playgroud)
然后我的一些模型中的以下内容:
default_scope :conditions => { :account_id => (Thread.current[:account].id unless Thread.current[:account].nil?) }
Run Code Online (Sandbox Code Playgroud)
现在,这有效 - 有些时候.我举例说明了加载索引方法并获取应用了作用域的记录列表,但有时候得到一个空列表,因为Thread.current [:account_id]的结果为nil,即使请求中较早的查询正在运行使用相同的值.
问题是,为什么这不起作用,是否有更好的方法来设置当前请求的全局变量?