Class: Mechanize::DirectorySaver

Inherits:
Download
  • Object
show all
Defined in:
lib/mechanize/directory_saver.rb

Overview

Unlike Mechanize::FileSaver, the directory saver places all downloaded files in a single pre-specified directory.

You must register the directory to save to before using the directory saver:

agent.pluggable_parser['image'] = \
  Mechanize::DirectorySaver.save_to 'images'

Constant Summary

Constants included from Parser

Parser::SPECIAL_FILENAMES

Instance Attribute Summary

Attributes inherited from Download

#body_io, #filename

Attributes included from Parser

#code, #response, #uri

Class Method Summary collapse

Instance Method Summary collapse

Methods inherited from Download

#body, #save, #save!

Methods included from Parser

#extract_filename, #fill_header, #find_free_name

Constructor Details

#initialize(uri = nil, response = nil, body_io = nil, code = nil) ⇒ DirectorySaver

Saves the body_io into the directory specified for this DirectorySaver by save_to. The filename is chosen by Mechanize::Parser#extract_filename.

Raises:



57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
# File 'lib/mechanize/directory_saver.rb', line 57

def initialize uri = nil, response = nil, body_io = nil, code = nil
  directory = self.class.directory

  raise Mechanize::Error,
    'no save directory specified - ' \
    'use Mechanize::DirectorySaver.save_to ' \
    'and register the resulting class' unless directory

  super

  @filename = CGI.unescape(@filename) if self.class.decode_filename?
  path = File.join directory, @filename

  if self.class.overwrite?
    save! path
  else
    save path
  end
end

Class Method Details

.decode_filename?Boolean

True if downloaded files should have their names decoded before saving.

Returns:

  • (Boolean)


42
43
44
# File 'lib/mechanize/directory_saver.rb', line 42

def self.decode_filename?
  @options[:decode_filename]
end

.directoryObject

The directory downloaded files will be saved to.



35
36
37
# File 'lib/mechanize/directory_saver.rb', line 35

def self.directory
  @directory
end

.overwrite?Boolean

Checks if overwrite parameter is set to true

Returns:

  • (Boolean)


49
50
51
# File 'lib/mechanize/directory_saver.rb', line 49

def self.overwrite?
  @options[:overwrite]
end

.save_to(directory, options = {}) ⇒ Object

Creates a DirectorySaver subclass that will save responses to the given directory. If options includes a decode_filename value set to true then the downloaded filename will be ran through CGI.unescape before being saved. If options includes a overwrite value set to true then downloaded file will be overwritten if two files with the same names exist.



23
24
25
26
27
28
29
30
# File 'lib/mechanize/directory_saver.rb', line 23

def self.save_to directory, options = {}
  directory = File.expand_path directory

  Class.new self do |klass|
    klass.instance_variable_set :@directory, directory
    klass.instance_variable_set :@options, options
  end
end