Class: Wordnik::Response

Inherits:
Object show all
Extended by:
ActiveModel::Naming
Includes:
ActiveModel::Conversion, ActiveModel::Validations
Defined in:
lib/wordnik/response.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(raw) ⇒ Response

Returns a new instance of Response.



16
17
18
19
20
21
22
23
# File 'lib/wordnik/response.rb', line 16

def initialize(raw)
  self.raw = raw

  case self.code
  when 500..510 then raise(ServerError, self.error_message)
  when 299..426 then raise(ClientError, self.error_message)
  end
end

Instance Attribute Details

#rawObject

Returns the value of attribute raw.



12
13
14
# File 'lib/wordnik/response.rb', line 12

def raw
  @raw
end

Instance Method Details

#bodyObject

If body is JSON, parse it TODO: If body is XML, parse it Otherwise return raw string



38
39
40
41
42
# File 'lib/wordnik/response.rb', line 38

def body
  JSON.parse raw.body
rescue
  raw.body
end

#codeObject



25
26
27
# File 'lib/wordnik/response.rb', line 25

def code
  raw.code
end

#error_messageObject



29
30
31
32
33
# File 'lib/wordnik/response.rb', line 29

def error_message
  body['message']
rescue
  body
end

#formatObject

Extract the response format from the header hash e.g. => ‘application/json’



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

def format
  headers['Content-Type'].split("/").last.to_s
end

#headersObject



44
45
46
47
48
# File 'lib/wordnik/response.rb', line 44

def headers
  h = {}
  raw.headers_hash.each {|k,v| h[k] = v }
  h
end

#json?Boolean

Returns:

  • (Boolean)


56
57
58
# File 'lib/wordnik/response.rb', line 56

def json?
  format == 'json'
end

#persisted?Boolean

It’s an ActiveModel thing..

Returns:

  • (Boolean)


82
83
84
# File 'lib/wordnik/response.rb', line 82

def persisted?
  false
end

#pretty_bodyObject



64
65
66
67
68
69
70
71
72
73
74
75
# File 'lib/wordnik/response.rb', line 64

def pretty_body
  return unless body.present?
  case format
  when 'json'
    JSON.pretty_generate(body).gsub(/\n/, '<br/>')
  when 'xml'
    xsl = Nokogiri::XSLT(File.open(File.join(File.dirname(__FILE__), "../../config/pretty_print.xsl")))
    xml = Nokogiri(body)
    coder = HTMLEntities.new
    coder.encode(xsl.apply_to(xml).to_s)
  end
end

#pretty_headersObject



77
78
79
# File 'lib/wordnik/response.rb', line 77

def pretty_headers
  JSON.pretty_generate(headers).gsub(/\n/, '<br/>')
end

#xml?Boolean

Returns:

  • (Boolean)


60
61
62
# File 'lib/wordnik/response.rb', line 60

def xml?
  format == 'xml'
end