Class: Anyicon::Common
- Inherits:
-
Object
- Object
- Anyicon::Common
- Defined in:
- lib/anyicon/common.rb
Overview
The Common class provides utility methods that can be used across the Anyicon gem. This class includes methods for making HTTP requests, handling redirects, and fetching content from specified URLs. It ensures that the HTTP requests follow redirects up to a specified limit to prevent infinite loops.
Example usage:
common = Anyicon::Common.new
response = common.fetch('https://example.com')
puts response.body if response.is_a?(Net::HTTPSuccess)
Direct Known Subclasses
Constant Summary collapse
- ALLOWED_HOSTS =
%w[github.com raw.githubusercontent.com objects.githubusercontent.com api.github.com].freeze
Instance Method Summary collapse
-
#fetch(url, limit = 10) ⇒ Net::HTTPResponse
Fetches the content from the given URL, following redirects if necessary.
Instance Method Details
#fetch(url, limit = 10) ⇒ Net::HTTPResponse
Fetches the content from the given URL, following redirects if necessary.
23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 |
# File 'lib/anyicon/common.rb', line 23 def fetch(url, limit = 10) raise Net::HTTPError.new("Too many HTTP redirects", nil) if limit.zero? return nil if url.nil? uri = URI.parse(URI::RFC2396_PARSER.escape(url)) unless uri.is_a?(URI::HTTPS) && ALLOWED_HOSTS.include?(uri.host) raise Net::HTTPError.new("Blocked request to disallowed host: #{uri.host}", nil) end request = Net::HTTP::Get.new(uri) token = Anyicon.configuration.github_token request["Authorization"] = "token #{token}" if token response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: true) do |http| http.request(request) end case response when Net::HTTPSuccess then response when Net::HTTPRedirection then fetch(response["location"], limit - 1) else response.error! end end |