I'm putting together a small app which will allow a user to log into a semi-popular social networking site that doesn't have a sufficient API, so I'm using the mechanize gem to automate a few functions I wanted to add for anyone to use, such as bulk messaging.
Because of the API restrictions, I'm forced to do this by pretending to be a user interacting with the http interface of the site.
The problem I'm having is once a user logs in to my site, how can I keep the cookie from the social networking site statefully in the session so they don't need to enter credentials for every page load?
I was trying to marshal the cookie from the mechanize instance but I received errors regarding mutex's not having a Marshal method.
EDIT - Solved
Turned out to be quite simple, but the documentation sure didn't help the matter, just because of incompleteness.
Here's what I did to catch the cookies and bring them back for future requests (much inbetween code and error checking excluded for brevity):
users_controller.rb
def create
session.delete(:agent) if session[:agent]
agent = Mechanize.new
page = agent.get('www.socialnetwork.com/login')
login_form = page.form
login_form.email = params[:login][:email]
login_form.password = params[:login][:password]
page = agent.submit(login_form, login_form.buttons.first)
cookies = agent.cookie_jar.store.map {|i| i}
session[:agent] = Marshal.dump cookies
redirect_to root_path
end
application_controller.rb
before_filter :set_agent
def set_agent
if session[:agent]
@agent = Mechanize.new
cookies = Marshal.load session[:agent]
cookies.each {|i| @agent.cookie_jar.store.add i}
end
end