class Prefetcher::HttpFetcher
Attributes
memoizer[R]
redis_connection[R]
url[R]
Public Class Methods
new(params = {})
click to toggle source
# 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
Public Instance Methods
fetch()
click to toggle source
Makes request to given URL
# 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
get()
click to toggle source
Returns cached version if availible. If not cached - makes request using fetch
.
# File lib/prefetcher/http_fetcher.rb, line 29 def get (get_from_memory || fetch).html_safe.force_encoding('utf-8') end
Protected Instance Methods
cache_key()
click to toggle source
# File lib/prefetcher/http_fetcher.rb, line 34 def cache_key "cached-url-#{url}" end
get_from_memory()
click to toggle source
# File lib/prefetcher/http_fetcher.rb, line 38 def get_from_memory @redis_connection.get(cache_key) end
memoize(response)
click to toggle source
# File lib/prefetcher/http_fetcher.rb, line 42 def memoize(response) memoizer.push(url) @redis_connection.set(cache_key, response) end