| Class | WWW::Mechanize::FileSaver |
| In: |
lib/www/mechanize/file_saver.rb
|
| Parent: | File |
This is a pluggable parser that automatically saves every file it encounters. It saves the files as a tree, reflecting the host and file path.
require 'rubygems'
require 'mechanize'
agent = WWW::Mechanize.new
agent.pluggable_parser.pdf = WWW::Mechanize::FileSaver
agent.get('http://example.com/foo.pdf')
| filename | [R] |
# File lib/www/mechanize/file_saver.rb, line 19
19: def initialize(uri=nil, response=nil, body=nil, code=nil)
20: super(uri, response, body, code)
21: path = uri.path.empty? ? 'index.html' : uri.path.gsub(/^[\/]*/, '')
22: path += 'index.html' if path =~ /\/$/
23:
24: split_path = path.split(/\//)
25: filename = split_path.length > 0 ? split_path.pop : 'index.html'
26: joined_path = split_path.join(::File::SEPARATOR)
27: path = if joined_path.empty?
28: uri.host
29: else
30: "#{uri.host}#{::File::SEPARATOR}#{joined_path}"
31: end
32:
33: @filename = "#{path}#{::File::SEPARATOR}#{filename}"
34: FileUtils.mkdir_p(path)
35: save_as(@filename)
36: end