| Class | Mechanize::FileSaver |
| In: |
lib/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 = Mechanize.new
agent.pluggable_parser.pdf = Mechanize::FileSaver
agent.get('http://example.com/foo.pdf')
| filename | [R] |
# File lib/mechanize/file_saver.rb, line 18
18: def initialize(uri=nil, response=nil, body=nil, code=nil)
19: super(uri, response, body, code)
20: path = uri.path.empty? ? 'index.html' : uri.path.gsub(/^[\/]*/, '')
21: path += 'index.html' if path =~ /\/$/
22:
23: split_path = path.split(/\//)
24: filename = split_path.length > 0 ? split_path.pop : 'index.html'
25: joined_path = split_path.join(::File::SEPARATOR)
26: path = if joined_path.empty?
27: uri.host
28: else
29: "#{uri.host}#{::File::SEPARATOR}#{joined_path}"
30: end
31:
32: @filename = "#{path}#{::File::SEPARATOR}#{filename}"
33: FileUtils.mkdir_p(path)
34: save_as(@filename)
35: end