How can I use an object in different methods within the same controller?

守給你的承諾、 提交于 2020-01-07 04:07:07

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!