我有一个无数据库的rails应用程序,可与API通信。
对于身份验证,我将用户凭据发送到api,并在成功时接收会话令牌。随后,我发出的每个api请求都应该包含该令牌。
api_request.rb:
class ApiRequest
def initialize(relative_path,params={})
params = _add_base_data params
send_request relative_path, params
end
private
def send_request(relative_path,params)
conn = Faraday.new(:url => MyApp::Application.config.server) do |faraday|
faraday.request :url_encoded
faraday.response :logger
faraday.adapter Faraday.default_adapter
end
encoded = conn.post relative_path,params
@data = JSON.parse encoded.body
@data
end
def _add_base_data params
params[:session_token] = ?
params
end
end
my_session.rb:
class MySession
def login? email,pass
params = { :email => email, :password => pass }
resp = ApiRequest.new '/user/login', params
if resp.failed?
false
else
@session[:token] = resp.data['session_token']
true
end
end
end
如何为每次通话使会话令牌可用于ApiRequest模型?
答案 0 :(得分:1)
如何将会话令牌作为参数传递给ApiRequest
呢?然后,您可以使用一种简单的方法将调用包装起来,以便在控制器中使用:
# in base controller class
def api(resource, params)
ApiRequest.new @session[:token], '/user/login', params
end
这样做的好处是会话参数保持在控制器级别,从而无需在模型中保留状态信息(可能不应该存在)。