Class: Mechanize::FileSaver

Inherits:
File
  • Object
show all
Defined in:
lib/mechanize/file_saver.rb

Overview

Synopsis

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.

Example to save all PDF’s

require 'rubygems'
require 'mechanize'

agent = Mechanize.new
agent.pluggable_parser.pdf = Mechanize::FileSaver
agent.get('http://example.com/foo.pdf')

Instance Attribute Summary collapse

Attributes inherited from File

#body, #code, #response, #uri

Instance Method Summary collapse

Methods inherited from File

#save_as

Constructor Details

#initialize(uri = nil, response = nil, body = nil, code = nil) ⇒ FileSaver

Returns a new instance of FileSaver.



18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
# File 'lib/mechanize/file_saver.rb', line 18

def initialize(uri=nil, response=nil, body=nil, code=nil)
  super(uri, response, body, code)
  path = uri.path.empty? ? 'index.html' : uri.path.gsub(/^[\/]*/, '')
  path += 'index.html' if path =~ /\/$/

  split_path = path.split(/\//)
  filename = split_path.length > 0 ? split_path.pop : 'index.html'
  joined_path = split_path.join(::File::SEPARATOR)
  path = if joined_path.empty?
           uri.host
         else
           "#{uri.host}#{::File::SEPARATOR}#{joined_path}"
         end

  @filename = "#{path}#{::File::SEPARATOR}#{filename}"
  FileUtils.mkdir_p(path)
  save_as(@filename)
end

Instance Attribute Details

#filenameObject (readonly)

Returns the value of attribute filename.



16
17
18
# File 'lib/mechanize/file_saver.rb', line 16

def filename
  @filename
end