class DataKitten::Fetcher

Attributes

url[R]

Public Class Methods

new(url) click to toggle source
# File lib/data_kitten/fetcher.rb, line 15
def initialize(url)
  @url = url
end
wrap(url_or_fetcher) click to toggle source
# File lib/data_kitten/fetcher.rb, line 7
def self.wrap(url_or_fetcher)
  if url_or_fetcher.is_a?(self)
    url_or_fetcher
  else
    new(url_or_fetcher)
  end
end

Public Instance Methods

as_json() click to toggle source
# File lib/data_kitten/fetcher.rb, line 41
def as_json
  JSON.parse(body) if response
rescue JSON::ParserError
  nil
end
body() click to toggle source
# File lib/data_kitten/fetcher.rb, line 37
def body
  response if response
end
code() click to toggle source
# File lib/data_kitten/fetcher.rb, line 33
def code
  response ? response.code : @code
end
content_type() click to toggle source
# File lib/data_kitten/fetcher.rb, line 47
def content_type
  response.headers[:content_type] if response
end
content_type_format() click to toggle source
# File lib/data_kitten/fetcher.rb, line 51
def content_type_format
  if val = content_type
    val.split(';').first
  end
end
exists?() click to toggle source
# File lib/data_kitten/fetcher.rb, line 19
def exists?
  if @requested
    ok?
  else
    RestClient.head(url).code == 200
  end
rescue RestClient::ExceptionWithResponse => error
  false
end
html?() click to toggle source
# File lib/data_kitten/fetcher.rb, line 61
def html?
  !!(content_type_format =~ %r{^text/html}i)
end
json?() click to toggle source
# File lib/data_kitten/fetcher.rb, line 65
def json?
  !!(content_type_format =~ %r{^application/json}i)
end
ok?() click to toggle source
# File lib/data_kitten/fetcher.rb, line 29
def ok?
  code == 200
end
to_s() click to toggle source
# File lib/data_kitten/fetcher.rb, line 57
def to_s
  url.to_s
end

Private Instance Methods

response() click to toggle source
# File lib/data_kitten/fetcher.rb, line 70
def response
  unless @requested
    @requested = true
    begin
      @response = RestClient.get(url)
    rescue RestClient::ExceptionWithResponse => error
      @error = error.response
      @code = @error.code
    end
  end
  @response
end