Class: Prefetcher::HttpFetcher

Inherits:
Object
  • Object
show all
Defined in:
lib/prefetcher/http_fetcher.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(params = {}) ⇒ HttpFetcher

Returns a new instance of HttpFetcher.



5
6
7
8
9
# File 'lib/prefetcher/http_fetcher.rb', line 5

def initialize(params = {})
  @url = params.fetch(:url)
  @redis_connection = params.fetch(:redis_connection, Prefetcher.redis_connection)
  @memoizer = params.fetch(:memoizer, HttpMemoizer.new(redis_connection: @redis_connection))
end

Instance Attribute Details

#memoizerObject (readonly)

Returns the value of attribute memoizer.



3
4
5
# File 'lib/prefetcher/http_fetcher.rb', line 3

def memoizer
  @memoizer
end

#redis_connectionObject (readonly)

Returns the value of attribute redis_connection.



3
4
5
# File 'lib/prefetcher/http_fetcher.rb', line 3

def redis_connection
  @redis_connection
end

#urlObject (readonly)

Returns the value of attribute url.



3
4
5
# File 'lib/prefetcher/http_fetcher.rb', line 3

def url
  @url
end

Instance Method Details

#fetchObject

Makes request to given URL



12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
# File 'lib/prefetcher/http_fetcher.rb', line 12

def fetch
  uri = URI(URI.encode(self.url))

  http = Net::HTTP.new(uri.host, uri.port)
  request = Net::HTTP::Get.new(uri.request_uri)

  response = http.request(request)

  if response.code == "200"
    memoize(response.body)
    response.body
  else
    ''
  end
end

#getObject

Returns cached version if availible. If not cached - makes request using #fetch .



29
30
31
# File 'lib/prefetcher/http_fetcher.rb', line 29

def get
  (get_from_memory || fetch).html_safe.force_encoding('utf-8')
end