Class: DataKitten::Fetcher

Inherits:
Object
  • Object
show all
Defined in:
lib/data_kitten/fetcher.rb

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(url) ⇒ Fetcher

Returns a new instance of Fetcher.



15
16
17
# File 'lib/data_kitten/fetcher.rb', line 15

def initialize(url)
  @url = url
end

Instance Attribute Details

#urlObject (readonly)

Returns the value of attribute url.



5
6
7
# File 'lib/data_kitten/fetcher.rb', line 5

def url
  @url
end

Class Method Details

.wrap(url_or_fetcher) ⇒ Object



7
8
9
10
11
12
13
# 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

Instance Method Details

#as_jsonObject



41
42
43
44
45
# File 'lib/data_kitten/fetcher.rb', line 41

def as_json
  JSON.parse(body) if response
rescue JSON::ParserError
  nil
end

#bodyObject



37
38
39
# File 'lib/data_kitten/fetcher.rb', line 37

def body
  response if response
end

#codeObject



33
34
35
# File 'lib/data_kitten/fetcher.rb', line 33

def code
  response ? response.code : @code
end

#content_typeObject



47
48
49
# File 'lib/data_kitten/fetcher.rb', line 47

def content_type
  response.headers[:content_type] if response
end

#content_type_formatObject



51
52
53
54
55
# File 'lib/data_kitten/fetcher.rb', line 51

def content_type_format
  if val = content_type
    val.split(';').first
  end
end

#exists?Boolean

Returns:

  • (Boolean)


19
20
21
22
23
24
25
26
27
# 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?Boolean

Returns:

  • (Boolean)


61
62
63
# File 'lib/data_kitten/fetcher.rb', line 61

def html?
  !!(content_type_format =~ %r{^text/html}i)
end

#json?Boolean

Returns:

  • (Boolean)


65
66
67
# File 'lib/data_kitten/fetcher.rb', line 65

def json?
  !!(content_type_format =~ %r{^application/json}i)
end

#ok?Boolean

Returns:

  • (Boolean)


29
30
31
# File 'lib/data_kitten/fetcher.rb', line 29

def ok?
  code == 200
end

#to_sObject



57
58
59
# File 'lib/data_kitten/fetcher.rb', line 57

def to_s
  url.to_s
end