Class: Anyicon::Common

Inherits:
Object
  • Object
show all
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

Collection, Icon

Instance Method Summary collapse

Instance Method Details

#fetch(url, limit = 10) ⇒ Net::HTTPResponse

Fetches the content from the given URL, following redirects if necessary.

Parameters:

  • url (String)

    the URL to fetch

  • limit (Integer) (defaults to: 10)

    the maximum number of redirects to follow (default is 10)

Returns:

  • (Net::HTTPResponse)

    the HTTP response

Raises:

  • (Net::HTTPError)

    if the number of redirects exceeds the limit or another HTTP error occurs



21
22
23
24
25
26
27
28
29
30
31
32
33
34
# File 'lib/anyicon/common.rb', line 21

def fetch(url, limit = 10)
  raise Net::HTTPError, 'Too many HTTP redirects' if limit.zero?
  return nil if url.nil?

  uri = URI.parse(URI::DEFAULT_PARSER.escape(url))
  response = Net::HTTP.get_response(uri)

  case response
  when Net::HTTPSuccess then response
  when Net::HTTPRedirection then fetch(response['location'], limit - 1)
  else
    response.error!
  end
end