问题
I have a controller with different methods.
In the first method, authorize
I instantiate an object which I would like to reuse in another method. The problem is that both methods have different views, and the controller instance does not remain the same.
Hers is my code
def authorize
@session ||= get_session
puts @session
@authorize_url = @session.get_authorize_url
end
def list
puts self
@session ||= get_session
@client = DropboxClient.new(@session, ACCESS_TYPE)
metadata = get_meta_data("/")
@files = []
metadata.each do |data|
@files.push data
end
@files
end
So how can I reuse the @session variable?
Best Phil
回答1:
You don't, really. Each public method in your controller that renders a view is meant to be an endpoint for a request. The request's lifecycle ends there.
To persist data between requests, you should use sessions. This might be a bit more confusing, since you are indeed trying to persist an instance variable called @session
between requests, but that's what they're for.
Rails exposes session data through a session
hash available in your controllers. More information about how Rails handles sessions is available in the Rails Documentation
class YourController < ApplicationController
def authorize
@session ||= get_session
session[:dropbox_session] = @session
end
def list
@client = DropboxClient.new(session[:dropbox_session], ACCESS_TYPE)
end
end
来源:https://stackoverflow.com/questions/11512242/how-can-i-use-an-object-in-different-methods-within-the-same-controller