Class: Sinew::Response

Inherits:
SimpleDelegator
  • Object
show all
Defined in:
lib/sinew/response.rb

Overview

A wrapper around Faraday::Response, with some parsing helpers.

Instance Method Summary collapse

Instance Method Details

#diskpathObject

Return the cache diskpath for this response



52
53
54
# File 'lib/sinew/response.rb', line 52

def diskpath
  env[:httpdisk_diskpath]
end

#htmlObject

Like body, but tries to cleanup whitespace around HTML for easier parsing.



10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
# File 'lib/sinew/response.rb', line 10

def html
  @html ||= body.dup.tap do
    # fix invalid utf8
    if _1.encoding == Encoding::UTF_8
      _1.encode!('UTF-8', invalid: :replace, undef: :replace, replace: '?')
    end

    # squish
    _1.strip!
    _1.gsub!(/\s+/, ' ')

    # kill whitespace around tags
    _1.gsub!(/ ?<([^>]+)> ?/, '<\\1>')
  end
end

#jsonObject

Return body as JSON



27
28
29
# File 'lib/sinew/response.rb', line 27

def json
  @json ||= JSON.parse(body, symbolize_names: true)
end

#mashObject

Return JSON body as Hashie::Mash



32
33
34
# File 'lib/sinew/response.rb', line 32

def mash
  @mash ||= Hashie::Mash.new(json)
end

#nokoObject

Return body HTML as Nokogiri document



37
38
39
# File 'lib/sinew/response.rb', line 37

def noko
  @noko ||= Nokogiri::HTML(html)
end

#uncacheObject

Remove cached response from disk, if any



57
58
59
# File 'lib/sinew/response.rb', line 57

def uncache
  File.unlink(diskpath) if File.exist?(diskpath)
end

#urlObject

Return the final URI for the request, after redirects



47
48
49
# File 'lib/sinew/response.rb', line 47

def url
  env.url
end

#xmlObject

Return body XML as Nokogiri document



42
43
44
# File 'lib/sinew/response.rb', line 42

def xml
  @xml ||= Nokogiri::XML(html)
end