Search code examples
ruby-on-railsrubygmail-apiopenstruct

Pass Gmail Connection to sidekiq


require gmail
gmail = Gmail.connect("[email protected]", "password")
SidekiqWorker.perform_async(gmail, item.user_id)
gmail.logout()

I want to pass a object to sidekiq,It is a gmail client object,And I don't want to create that object in perform method ,so I am passing and its going in string format , I am taking the help of open struct to pass it, But its going in string format.

#OpenStruct gmail=#Gmail::Client0xbe18230 ([email protected]) connected>>

Solution

  • There are a couple of issues. I do not think the code above will work as you intend. The SidekiqWork is run asynchronously with the rest of the code. It looks like your code might be subject to a race condition. You cannot control if the worker code runs before or after the gmail.logout() call.

    In addition, it's generally not considered a best practice to pass an object as an argument to a Sidekiq job. See the Sidekiq Best Practices. Instead, I might consider making the gmail connection from within the Sidekiq job.

    As an alternative, you might consider using a class method in a lib class that stores an instance of the gmail client. You can memoize this connection like the following:

     class GmailClient
       def self.connection
         @client ||= Gmail.connect("[email protected]", "password")
       end
     end