Class | WWW::Mechanize::File |
In: |
lib/www/mechanize/file.rb
|
Parent: | Object |
This is the default (and base) class for the Pluggable Parsers. If Mechanize cannot find an appropriate class to use for the content type, this class will be used. For example, if you download a JPG, Mechanize will not know how to parse it, so this class will be instantiated.
This is a good class to use as the base class for building your own pluggable parsers.
require 'rubygems' require 'mechanize' agent = WWW::Mechanize.new agent.get('http://example.com/foo.jpg').class #=> WWW::Mechanize::File
response | -> | header |
body | -> | content |
body | [RW] | |
code | [RW] | |
filename | [RW] | |
response | [RW] | |
uri | [RW] |
# File lib/www/mechanize/file.rb, line 25 25: def initialize(uri=nil, response=nil, body=nil, code=nil) 26: @uri, @body, @code = uri, body, code 27: @response = Headers.new 28: 29: # Copy the headers in to a hash to prevent memory leaks 30: if response 31: response.each { |k,v| 32: @response[k] = v 33: } 34: end 35: 36: @filename = 'index.html' 37: 38: # Set the filename 39: if disposition = @response['content-disposition'] 40: disposition.split(/;\s*/).each do |pair| 41: k,v = pair.split(/=/, 2) 42: @filename = v if k.downcase == 'filename' 43: end 44: else 45: if @uri 46: @filename = @uri.path.split(/\//).last || 'index.html' 47: @filename << ".html" unless @filename =~ /\./ 48: end 49: end 50: 51: yield self if block_given? 52: end
Use this method to save the content of this object to filename
# File lib/www/mechanize/file.rb, line 55 55: def save_as(filename = nil) 56: if filename.nil? 57: filename = @filename 58: number = 1 59: while(::File.exists?(filename)) 60: filename = "#{@filename}.#{number}" 61: number += 1 62: end 63: end 64: 65: ::File::open(filename, "wb") { |f| 66: f.write body 67: } 68: end