Search code examples
rubycookiesmechanizemechanize-ruby

Ruby::Mechanize::cookie_jar


I have a site that does four different re-directs and doesn't seem to always pass the cookies along.

So I've researched here and tried a few of the solutions like:

creating a temp cookie_jar and assigning that each time. I've also attempted to manually pass the cookies like so:

cookie = Mechanize::Cookie.new("TLSID",bot.cookie_jar.jar['.manageyourloans.com']    
["/"]["TLSID"].value)
cookie.domain = ".manageyourloans.com"
cookie.path = "/"
bot.cookie_jar.add(bot.history.last.uri,cookie)

cookie = Mechanize::Cookie.new("TLHID",bot.cookie_jar.jar['.manageyourloans.com']
["/"]["TLHID"].value)
cookie.domain = ".manageyourloans.com"
cookie.path = "/"
bot.cookie_jar.add(bot.history.last.uri,cookie)

The problem with the above is that if it doesn't need to be passed I get an error.
Is it possible to do the following. There are 10-12 different cookie values that seem to get passed, some with every page(redirect) or just a few of them. How do I do the above and manually pass the cookies, but if the value doesn't exist then just pass null?

Or is there a better way to do this?


Solution

  • I noticed a problem in the past with a certain version of mechanize when the cookie domain looks like: .domain.com and the request is for domain.com, the cookie would not get set.

    This may not be the best way to deal with it but my solution at the time was to monkey patch mechanize to strip out the domain part of the cookie:

    class Mechanize::Cookie
      class << self; alias_method :old_parse, :parse end
      def self.parse(uri, str, log = Mechanize.log, &block)
        str.gsub!(/domain[^;]*;/,'')
        old_parse(uri, str, log, &block)
      end
    end