tenderlove/mechanize — pull request #173 by kitamomonga (2011-12-09 01:39:36+00:00)
Title: agent.page.image_with(:caption => 'logo').fetch.save

To save images to disk with method chaining.

agent.get('http://ruby-lang.org/en/')
agent.page.image_with(:alt => "Ruby - A Programmer's Best Friend").fetch
p agent.page.uri.to_s #=> "http://www.ruby-lang.org/images/logo.gif"

Page#image_with, Page#images_with
-----------------------------
selection methods

Image#width, Image#height, Image#alt, Image#title, Image#dom_id, Image#dom_class
-------------------------------------------------------------------
methods for HTML attributes

Image#caption
------------
returns "caption", title attribute or alt attribute or "".
<legend> may be supported but not yet.

Image#pretty_print, #pretty_inspect
-----------------------------

p page.images[0] #=> #

Image#extname (alias #suffix)
------------------------
returns image url suffix like ".jpg".

Image#mime_type
--------------
returns image mime type (Using WEBrick::HTTPUtils::DefaultMimeTypes)
It does not come from real server response, but just url suffix.

p page.images[0].url #=> "http://example/test.jpg"
p page.images[0].suffix #=> ".jpg"
p page.images[0].mime_type #=> "image/jpg"

page.images_with(:mime_type => /gif|png|jpeg/).each ...

Image#fetch
----------
fetch the image with Mechanize#get (like Link#click).
I could not find better method name than "fetch"...

Image#save
---------
#fetch Image and #save.

# Mechanize 2.0.1
page.images.find_all{|x| x.src =~ /img/}.each{|img| agent.get(img.src, nil, page).save}

# from now on with Ruby 1.9.x
page.images_with(src: /img/).map(&:save)

Image#download
-------------
#save with Mechanize#transact. Image url is not added to history.

p agent.page.uri.to_s => "http://example/images.html"
agent.page.images[0].download
p agent.page.uri.to_s #=> "http://example/images.html"

p agent.page.uri.to_s => "http://example/images.html"
agent.page.images[0].save
p agent.page.uri.to_s #=> "http://example/test.jpg"