Class: Getvideo::Response

Inherits:
Object
  • Object
show all
Defined in:
lib/getvideo/video.rb

Constant Summary collapse

CONTENT_TYPE =
{
  'application/json' => :json,
  'application/x-www-form-urlencoded' => :html,
  'text/html' => :html,
  'text/javascript' => :json,
  'text/xml' => :xml,
  "text/plain" => :json
}
PARSERS =
{
  :json => lambda{ |body| MultiJson.respond_to?(:adapter) ? MultiJson.load(body) : MultiJson.decode(body) rescue body },
  :html => lambda{ |body| Nokogiri::HTML(body) },
  :xml => lambda{ |body| MultiXml.parse(body) }
}

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(response) ⇒ Response

Returns a new instance of Response.



62
63
64
# File 'lib/getvideo/video.rb', line 62

def initialize(response)
  @response = response
end

Instance Attribute Details

#responseObject (readonly)

Returns the value of attribute response.



60
61
62
# File 'lib/getvideo/video.rb', line 60

def response
  @response
end

Instance Method Details

#bodyObject



85
86
87
# File 'lib/getvideo/video.rb', line 85

def body
  decode(response.body)
end

#content_typeObject



108
109
110
# File 'lib/getvideo/video.rb', line 108

def content_type
  ((response.headers.values_at('content-type', 'Content-Type').compact.first || '').split(';').first || '').strip
end

#decode(body) ⇒ Object



89
90
91
92
93
94
95
96
97
98
99
100
101
102
# File 'lib/getvideo/video.rb', line 89

def decode(body)
  return '' if !body
  return body if json?
  charset = body.match(/charset\s*=[\s|\W]*([\w-]+)/)
  if charset[1].downcase != "utf-8"
    begin
      body.encode! "utf-8", charset[1], {:invalid => :replace}
    rescue
      body
    end
  else
    body
  end
end

#headersObject



81
82
83
# File 'lib/getvideo/video.rb', line 81

def headers
  response.headers
end

#json?Boolean

Returns:

  • (Boolean)


112
113
114
# File 'lib/getvideo/video.rb', line 112

def json?
  CONTENT_TYPE[content_type] == :json || !response.body.match(/\<html/)
end

#parsedObject



122
123
124
125
126
# File 'lib/getvideo/video.rb', line 122

def parsed
  return nil unless CONTENT_TYPE.key?(content_type)
  return nil unless PARSERS.key?(parser)
  @parsed ||= PARSERS[parser].call(body)
end

#parserObject



116
117
118
119
120
# File 'lib/getvideo/video.rb', line 116

def parser
  type = CONTENT_TYPE[content_type]
  type = :json if type == :html && !response.body.match(/\<html/)
  return type
end

#statusObject



104
105
106
# File 'lib/getvideo/video.rb', line 104

def status
  response.status
end