Class | Mechanize::File |
In: |
lib/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 = Mechanize.new agent.get('http://example.com/foo.jpg').class #=> Mechanize::File
response | -> | header |
body | -> | content |
body | [RW] | |
code | [RW] | |
filename | [RW] | |
response | [RW] | |
uri | [RW] |
# File lib/mechanize/file.rb, line 24 24: def initialize(uri=nil, response=nil, body=nil, code=nil) 25: @uri, @body, @code = uri, body, code 26: @response = Headers.new 27: 28: # Copy the headers in to a hash to prevent memory leaks 29: if response 30: response.each { |k,v| 31: @response[k] = v 32: } 33: end 34: 35: @filename = 'index.html' 36: 37: # Set the filename 38: if disposition = @response['content-disposition'] 39: disposition.split(/;\s*/).each do |pair| 40: k,v = pair.split(/=/, 2) 41: @filename = v if k && k.downcase == 'filename' 42: end 43: else 44: if @uri 45: @filename = @uri.path.split(/\//).last || 'index.html' 46: @filename << ".html" unless @filename =~ /\./ 47: end 48: end 49: 50: yield self if block_given? 51: end
Use this method to save the content of this object to filename
# File lib/mechanize/file.rb, line 54 54: def save_as(filename = nil) 55: if filename.nil? 56: filename = @filename 57: number = 1 58: while(::File.exists?(filename)) 59: filename = "#{@filename}.#{number}" 60: number += 1 61: end 62: end 63: 64: ::File::open(filename, "wb") { |f| 65: f.write body 66: } 67: end