Class: Mechanize::File

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

Overview

This is the base class for the Pluggable Parsers. If Mechanize cannot find an appropriate class to use for the content type, this class will be used. For example, if you download an image/jpeg, Mechanize will not know how to parse it, so this class will be instantiated.

This is a good class to use as the base class for building your own pluggable parsers.

Example

require 'mechanize'

agent = Mechanize.new
agent.get('http://example.com/foo.jpg').class  #=> Mechanize::File

Direct Known Subclasses

Page

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 = nil, code = nil) {|_self| ... } ⇒ File

Creates a new file retrieved from the given uri and response object. The body is the HTTP response body and code is the HTTP status.

Yields:

  • (_self)

Yield Parameters:



38
39
40
41
42
43
44
45
46
47
48
49
# File 'lib/mechanize/file.rb', line 38

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

  @full_path = false unless defined? @full_path

  fill_header response
  extract_filename

  yield self if block_given?
end

Instance Attribute Details

#bodyObject Also known as: content

The HTTP response body, the raw file contents



24
25
26
# File 'lib/mechanize/file.rb', line 24

def body
  @body
end

#filenameObject

The filename for this file based on the content-disposition of the response or the basename of the URL



30
31
32
# File 'lib/mechanize/file.rb', line 30

def filename
  @filename
end

Instance Method Details

#save(filename = nil) ⇒ Object Also known as: save_as

Use this method to save the content of this object to filename



54
55
56
57
58
59
60
# File 'lib/mechanize/file.rb', line 54

def save filename = nil
  filename = find_free_name filename

  open filename, 'wb' do |f|
    f.write body
  end
end