class WWW::Mechanize::File
agent.get(‘example.com/foo.jpg’).class #=> WWW::Mechanize::File
agent = WWW::Mechanize.new
require ‘mechanize’
require ‘rubygems’
== Example
pluggable parsers.
This is a good class to use as the base class for building your own
will not know how to parse it, so this class will be instantiated.
this class will be used. For example, if you download a JPG, Mechanize
Mechanize cannot find an appropriate class to use for the content type,
This is the default (and base) class for the Pluggable Parsers. If
= Synopsis
def initialize(uri=nil, response=nil, body=nil, code=nil)
def initialize(uri=nil, response=nil, body=nil, code=nil) @uri, @body, @code = uri, body, code @response = Headers.new # Copy the headers in to a hash to prevent memory leaks if response response.each { |k,v| @response[k] = v } end @filename = 'index.html' # Set the filename if disposition = @response['content-disposition'] disposition.split(/;\s*/).each do |pair| k,v = pair.split(/=/, 2) @filename = v if k.downcase == 'filename' end else if @uri @filename = @uri.path.split(/\//).last || 'index.html' @filename << ".html" unless @filename =~ /\./ end end yield self if block_given? end
def save_as(filename = nil)
def save_as(filename = nil) if filename.nil? filename = @filename number = 1 while(::File.exists?(filename)) filename = "#{@filename}.#{number}" number += 1 end end ::File::open(filename, "wb") { |f| f.write body } end