ruby-on-rails - 在 Rails Controller 中存储对象的最佳方式( session 除外)?

标签 ruby-on-rails ruby session controller

我有一个 Rails Controller

class Controllername < application
  def method1
    obj = API_CALL
    session =obj.access_token 
     redirect_to redirect_url    #calls the API authorization end point 
                            #and redirects to action method2  
  end
  def method2    
    obj.call_after_sometime
  end
end

我在 method1 中调用一些 API 获取对象并在 session 中存储访问 token 和 secret 。 method1 完成它的 Action 。

一段时间后,我调用了 method2,现在 session (访问 token 、 secret )已正确存储。

但是,现在在 method2 中,我需要使用 OBJECT obj 调用 API call_after_sometime。但是,现在 obj 不可用,因为我没有将它存储在 session 中(我们将在存储加密对象时遇到 SSL 错误)。

我想知道在 method1 中存储 obj 的最佳方式是什么,以便稍后在 method2 中使用它

编辑:

当我尝试 Rails.cache 或 Session 时出现错误

 TypeError - no _dump_data is defined for class OpenSSL::X509::Certificate

谷歌搜索我发现当我在 session 中存储加密值时它会抛出这个错误。

最佳答案

您可以尝试缓存它,但要注意缓存键,如果每个用户的对象都是唯一的,则将用户 ID 添加到缓存键中

class Controllername < application
  def method1
    obj = API_CALL
    Rails.cache.write("some_api_namespace/#{current_user.id}", obj)
    session =obj.access_token 
  end
  def method2
    obj = Rails.cache.read("some_api_namespace/#{current_user.id}")
    obj.call_after_sometime
  end
end

如果当您尝试读取它时缓存可能不存在,那么您可以使用 fetch 而不是 read 如果它会调用 api没有找到数据

def method2
  obj = Rails.cache.fetch("some_api_namespace/#{current_user.id}") do
    method_1
  end
  obj.call_after_sometime
end

more info here我也是wrote about it here

关于ruby-on-rails - 在 Rails Controller 中存储对象的最佳方式( session 除外)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30119531/

相关文章:

ruby-on-rails - 如何在 Rails View 中遍历数组?

ruby-on-rails - 使用 Resque with Redis To Go 做后台任务有什么意义

ruby - 如何引用多个 User_ID 并将其保存到一个表单中并在 Rails 4 App 的索引/显示页面中显示所述 ID

ruby-on-rails - 如何在 Rails 中测试任意路由?

java - Spring Security更改登录用户的角色不会立即生效

ruby-on-rails - 如何为 Rails SimpleForm 选择框设置默认选定值

ruby - 如何在我的 .rb 文件中共享变量?

c# - session 状态跨子域共享 session ,VB.NET 网站 C# MVC 4 应用程序

java - 如何防止 Play 框架中同一帐户多次登录?

ruby-on-rails - 使用 CSV 库时流关闭 IO 错误