Search code examples
rubysessioncookiesmechanizemechanize-ruby

Sharing (Mechanize) sessions across different requests in multi-threaded environment?


I'm developing an application that uses Ruby's Mechanize to login to a password-protected site and consumes certain data feeds. My application, in turn, allows my users to query and operate on the data. Every time a new users visits my app, it logs in to the remote data source to fetch data.

Here's the question: The remote site allows sessions to last up to 24 hours. What would be the best solution for cutting out the multiple log-ins on the remote site?

There are multiple ways to accomplish this: serializing and saving the Mechanize object to a database, saving Mechanize's cookie/jar/session information to a shared file between requests, etc. I'm looking for best practices, and, most importantly a solution that will work on Heroku's multi-threaded environment.


Solution

  • Here's what I would do:

    • Make a rake task to log into the site with mechanize and save the cookie in a file or db. run it on a 24 hour schedule.
    • From your controller, unless you really need it, use something more lightweight than mechanize (net/http?) to send the cookie and make the request.