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
# File 'lib/wordnik/response.rb', line 16

def initialize(raw)
  self.raw = raw
  catch_errors
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



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

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

#catch_errorsObject



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

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

#codeObject



21
22
23
# File 'lib/wordnik/response.rb', line 21

def code
  raw.code
end

#error_messageObject

If the error message is not helpful, dump the whole response object



34
35
36
37
38
39
40
# File 'lib/wordnik/response.rb', line 34

def error_message
  msg = body['message']
  return self.raw.to_yaml if msg.blank? || msg =~ /system error/i || msg =~ /ServerError/
  return msg
rescue
  self.raw.to_yaml
end

#formatObject

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



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

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

#headersObject



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

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

#json?Boolean

Returns:

  • (Boolean)


63
64
65
# File 'lib/wordnik/response.rb', line 63

def json?
  format == 'json'
end

#persisted?Boolean

It’s an ActiveModel thing..

Returns:

  • (Boolean)


89
90
91
# File 'lib/wordnik/response.rb', line 89

def persisted?
  false
end

#pretty_bodyObject



71
72
73
74
75
76
77
78
79
80
81
82
# File 'lib/wordnik/response.rb', line 71

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



84
85
86
# File 'lib/wordnik/response.rb', line 84

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

#xml?Boolean

Returns:

  • (Boolean)


67
68
69
# File 'lib/wordnik/response.rb', line 67

def xml?
  format == 'xml'
end