Menu Sidebar
Menu

Avdi Grimm

Hacker; code documentarian.

Preserving session with Mechanize

Here’s one for the so-I’ll-find-it-next-time-I-google files.

Say you’re automating some website interactions with Mechanize.

Say these interactions require a slow login process of fetching a login page, filling in fields, submitting, and waiting for the response.

Say you reeeeeeally don’t want to have to wait for this login process every single time the task runs. With Mechanize, you can save and load the agent’s cookies to a YAML file.

(You can save the cookies in other formats too, but that’s beyond the scope of this article).

If you do this, you may be surprised to find that your logged-in session still isn’t preserved. That’s because by default, Mechanize skips session cookies when saving them.

But you can override this behavior with an option:

With the session flag set, Mechanize will write out the full contents of its cookie jar for later loading.

Ruby Guilty Pleasures

Here’s a bit of code that I both love and feel a bit guilty about.

This code locates a project’s “root directory” by ascending from the current directory until it finds a directory with a subdirectory named demos. (Don’t ask why this indicates the root directory). In case it never finds such a directory, it raises an exception.

Love, because it’s so expressive and uses so many of my favorite Ruby goodies.

Guilt, because it’s dense and not the most revealing code in the world. Nothing about it is “tricky” or obfuscated; it just packs a lot into a small space.

Ruby goodies featured in these three lines include:

Older Posts

Virtuous Code

"The three virtues of a programmer: laziness, impatience, and hubris" — Larry Wall

Newsletter

News, notes, and commentary from Avdi, weekly-ish.

Books and Screencasts

RubyTapas Screencasts

RubyTapas Screencasts

Small plates of gourmet Ruby code.

Confident Ruby

Confident Ruby cover

32 Patterns for joyful coding.

The Making of Cowsays.com

Confident Ruby cover

Watch me build an app in Sinatra and Rails

Objects on Rails

Objects on Rails

A developer notebook on applying classic Object-Oriented principles to Ruby on Rails projects.

Exceptional Ruby

Exceptional Ruby

The definitive guide to exceptions and failure handling in Ruby.

Archives

Categories