Search code examples
ruby-on-railsruby-on-rails-3ruby-on-rails-3.1ruby-on-rails-plugins

How to persist a gem model instance?


I have a model defined in a gem (Google::APIClient.new) and I've created an instance of that gem in my controller.

I want to share the instance across controller actions per each user so I need to persist it somehow. I've tried storing it in a sessions variable (session[:client] = Google::APIClient.new) and into a field of one my own models (User.goog_client = Google::APIClient.new) which didn't work. Is there a proper way of persisting a model from another gem per each user?

Thanks in advance!

Soln: Found a simpler soln, store the attributes in sessions then reload them into the model:

    session[:access_token] = client.authorization.access_token
    session[:refresh_token] = client.authorization.refresh_token
    session[:expires_in] = client.authorization.expires_in
    session[:issued_at] = client.authorization.issued_at

    client.authorization.access_token = session[:access_token] 
    client.authorization.refresh_token = session[:refresh_token]
    client.authorization.expires_in = session[:expires_in]
    client.authorization.issued_at = session[:issued_at]

Solution

  • It sounds like you might want to create a wrapper class for these objects that inherits from ActiveRecord::Base.

    The attributes on your wrapper object would be whatever information is required to instantiate the object via the gem. Then you would create (or override) a finder method that does so.

    class FooWrapper < ActiveRecord::Base
    
      attr_accessible :x, :y, :z
    
      def self.get_real_foo(wrapper_id)
        wrapper_obj = self.find(wrapper_id)
        return FooGem.new(wrapper_obj.x, wrapper_obj.y, wrapper_obj.z)
      end
    end
    

    You say you tried storing the object in the session and your models? How exactly did you go about that? This may not really be the best way to solve your problem... If you post more specifics we will be better able to help you down the right path.

    Edit Addition:

    If you want the gem instance to be tied to a specific user then make FooWrapper :belongs_to :user. When you instantiate the real gem instance then you use whatever user-specific information as needed.