Class: Wayfarer::Page

Inherits:
Object
  • Object
show all
Extended by:
Forwardable
Includes:
Finders
Defined in:
lib/wayfarer/page.rb

Overview

The representation of fetched pages

Instance Attribute Summary collapse

Instance Method Summary collapse

Methods included from Finders

#images, #javascripts, #links, #stylesheets

Constructor Details

#initialize(attrs = {}) ⇒ Page

Returns a new instance of Page.


33
34
35
36
37
38
# File 'lib/wayfarer/page.rb', line 33

def initialize(attrs = {})
  @uri         = attrs[:uri]
  @status_code = attrs[:status_code]
  @body        = attrs[:body]
  @headers     = attrs[:headers]
end

Instance Attribute Details

#bodyString

Returns the response body.

Returns:

  • (String)

    the response body.


27
28
29
# File 'lib/wayfarer/page.rb', line 27

def body
  @body
end

#headersHash (readonly)

Returns the response headers.

Returns:

  • (Hash)

    the response headers.


31
32
33
# File 'lib/wayfarer/page.rb', line 31

def headers
  @headers
end

#status_codeFixnum (readonly)

Returns the response status code.

Returns:

  • (Fixnum)

    the response status code.


23
24
25
# File 'lib/wayfarer/page.rb', line 23

def status_code
  @status_code
end

#uriURI (readonly)

Returns the URI of the page.

Returns:

  • (URI)

    the URI of the page.


19
20
21
# File 'lib/wayfarer/page.rb', line 19

def uri
  @uri
end

Instance Method Details

#docOpenStruct, ...

Returns a parsed representation of the fetched document depending on the Content-Type field.

Returns:

  • (OpenStruct)

    if the Content-Type field's sub-type is "json".

  • (Nokogiri::XML::Document)

    if the Content-Type field's sub-type is "xml".

  • (Nokogiri::HTML::Document)

    otherwise.


45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
# File 'lib/wayfarer/page.rb', line 45

def doc
  return @doc if @doc

  # If no Content-Type field is present, assume HTML/XML
  # TODO: Test
  unless @headers["content-type"]
    return @doc = Parsers::XMLParser.parse_html(@body)
  end

  content_type = @headers["content-type"].first
  sub_type = MIME::Types[content_type].first.sub_type

  # TODO: Tests
  @doc = case sub_type
         when "json"
           Parsers::JSONParser.parse(@body)
         when "xml"
           Parsers::XMLParser.parse_xml(@body)
         else
           Parsers::XMLParser.parse_html(@body)
         end
end