Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way (other than session) to store objects in Rails controller?

I have a 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

I am calling some API's in method1 getting a object and storing access token and secrets in a session. method1 finishes it's action.

After sometime I am calling method2, now the session(access token, secrets) is stored correctly.

But, now inside method2 I need to call the API call_after_sometime using the OBJECT obj.But, now obj is unavailable because I didn't store it in a session(We will get a SSL error storing encrypted objects).

I want to know what's the best way to store obj in method1 so that it can be used later in method2

EDIT:

when I tried Rails.cache or Session I am getting the error

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

Googling it I found when I store encrypted values in session it will throw this error.

like image 460
Balaji Radhakrishnan Avatar asked Mar 16 '23 03:03

Balaji Radhakrishnan


2 Answers

You can try caching it, but be careful of the caching key, if the object is unique per user then add the user id in the caching key

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

If there's a possibility that the cache might not be existent when you try to read it, then you could use fetch instead of read which will call the api if it doesn't find the data

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

more info here and I also wrote about it here

like image 105
Mohammad AbuShady Avatar answered Apr 06 '23 07:04

Mohammad AbuShady


Try this: write obj into a key in the session and read it out again in the second method.

class Controllername < application
  def method1
    obj = API_CALL
    session[:obj] = obj
  end
  def method2    
    if obj = session[:obj]
      obj.call_after_sometime
    end
  end
end
like image 34
Max Williams Avatar answered Apr 06 '23 07:04

Max Williams