class OpenGraphReader::Fetcher
Fetch an URI to retrieve its HTML body, if available.
@api private
Constants
- HEADERS
Public Class Methods
Source
# File lib/open_graph_reader/fetcher.rb, line 26 def initialize uri raise ArgumentError, "url needs to be an instance of URI" unless uri.is_a? URI @uri = uri @fetch_failed = false @connection = Faraday.default_connection.dup @connection.headers.replace(HEADERS) @head_response = nil @get_response = nil prepend_middleware Faraday::CookieJar if defined? Faraday::CookieJar prepend_middleware Faraday::FollowRedirects::Middleware if defined? Faraday::FollowRedirects end
Create a new fetcher.
@param [URI] uri the URI to fetch.
Public Instance Methods
Source
# File lib/open_graph_reader/fetcher.rb, line 71 def body fetch_body unless fetched? raise NoOpenGraphDataError, "No response body received for #{@uri}" if fetch_failed? raise NoOpenGraphDataError, "Did not receive a HTML site at #{@uri}" unless html? @get_response.body end
Retrieve the body
@todo Custom error class @raise [ArgumentError] The received content does not seems to be HTML. @return [String]
Source
# File lib/open_graph_reader/fetcher.rb, line 50 def fetch @get_response = @connection.get(@uri) rescue Faraday::Error @fetch_failed = true end
Fetch the full page.
@return [Faraday::Response,nil]
Also aliased as: fetch_body
Source
# File lib/open_graph_reader/fetcher.rb, line 60 def fetch_headers @head_response = @connection.head(@uri) rescue Faraday::Error @fetch_failed = true end
Fetch just the headers
@return [Faraday::Response,nil]
Source
# File lib/open_graph_reader/fetcher.rb, line 96 def fetched? fetch_failed? || !@get_response.nil? end
Whether the target URI was fetched.
@return [Bool]
Also aliased as: fetched_body?
Source
# File lib/open_graph_reader/fetcher.rb, line 104 def fetched_headers? fetch_failed? || !@get_response.nil? || !@head_response.nil? end
Whether the headers of the target URI were fetched.
@return [Bool]
Source
# File lib/open_graph_reader/fetcher.rb, line 82 def html? fetch_headers unless fetched_headers? response = @get_response || @head_response return false if fetch_failed? return false unless response return false unless response.success? return false unless response["content-type"] response["content-type"].include? "text/html" end
Whether the target URI seems to return HTML
@return [Bool]
Source
# File lib/open_graph_reader/fetcher.rb, line 43 def url @uri.to_s end
The URL to fetch
@return [String]
Private Instance Methods
Source
# File lib/open_graph_reader/fetcher.rb, line 110 def fetch_failed? @fetch_failed end
Source
# File lib/open_graph_reader/fetcher.rb, line 114 def prepend_middleware middleware return if @connection.builder.handlers.include? middleware @connection.builder.insert(0, middleware) end