Class: Mechanize::Download

Inherits:
Object
  • Object
show all
Includes:
Parser
Defined in:
lib/mechanize/download.rb

Overview

Download is a pluggable parser for downloading files without loading them into memory first. You may subclass this class to handle content types you do not wish to load into memory first.

See Mechanize::PluggableParser for instructions on using this class.

Direct Known Subclasses

FileSaver

Constant Summary

Constants included from Parser

Parser::SPECIAL_FILENAMES

Instance Attribute Summary collapse

Attributes included from Parser

#code, #response, #uri

Instance Method Summary collapse

Methods included from Parser

#extract_filename, #fill_header, #find_free_name

Constructor Details

#initialize(uri = nil, response = nil, body_io = nil, code = nil) {|_self| ... } ⇒ Download

Creates a new download retrieved from the given uri and response object. The body_io is an IO-like containing the HTTP response body and code is the HTTP status.

Yields:

  • (_self)

Yield Parameters:



24
25
26
27
28
29
30
31
32
33
34
35
# File 'lib/mechanize/download.rb', line 24

def initialize uri = nil, response = nil, body_io = nil, code = nil
  @uri      = uri
  @body_io  = body_io
  @code     = code

  @full_path = false unless defined? @full_path

  fill_header response
  extract_filename

  yield self if block_given?
end

Instance Attribute Details

#body_ioObject (readonly) Also known as: content

Accessor for the IO-like that contains the body



15
16
17
# File 'lib/mechanize/download.rb', line 15

def body_io
  @body_io
end

Instance Method Details

#save(filename = nil) ⇒ Object

Saves a copy of the body_io to filename



40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
# File 'lib/mechanize/download.rb', line 40

def save filename = nil
  filename = find_free_name filename

  dirname = File.dirname filename
  FileUtils.mkdir_p dirname

  # Ruby 1.8.7 implements StringIO#path, can't use respond_to? :path
  if StringIO === @body_io then
    open filename, 'wb' do |io|
      until @body_io.eof? do
        io.write @body_io.read 16384
      end
    end
  else
    FileUtils.mv @body_io.path, filename
  end
end