class StyleStats::Css::Fetch

Attributes

elements[RW]
stylesheets[RW]

Public Class Methods

new(path) click to toggle source
# File lib/style_stats/css/fetch.rb, line 5
def initialize(path)
  self.stylesheets = []
  self.elements = []
  get(path)
end

Private Instance Methods

find_elements(doc) click to toggle source
# File lib/style_stats/css/fetch.rb, line 36
def find_elements(doc)
  doc.xpath('//style').map(&:text)
end
find_stylesheets(doc, url) click to toggle source
# File lib/style_stats/css/fetch.rb, line 40
def find_stylesheets(doc, url)
  base = URI.parse(url)
  doc.xpath('//link[@rel="stylesheet"]').map do |node|
    uri = URI.parse(node.get("href"))
    uri.scheme = base.scheme unless uri.scheme
    uri.host = base.host unless uri.host
    uri.port = base.port unless uri.port
    uri.to_s
  end
end
get(path) click to toggle source
# File lib/style_stats/css/fetch.rb, line 12
def get(path)
  if path =~ URI::regexp
    request(path)
  else
    self.stylesheets.push(open(path).read)
  end
end
options() click to toggle source
# File lib/style_stats/css/fetch.rb, line 51
def options
  options = if StyleStats.configuration.options[:requestOptions][:headers]['User-Agent']
              StyleStats.configuration.options[:requestOptions][:headers]
            else
              { 'User-Agent' => "Ruby/StyleStats #{StyleStats::VERSION}" }
            end
  options.merge(ssl_verify_mode: OpenSSL::SSL::VERIFY_NONE)
end
request(path) click to toggle source
# File lib/style_stats/css/fetch.rb, line 20
def request(path)
  file = open(path, options)
  case file.content_type
  when 'text/css'
    self.stylesheets.push(file.read)
  when 'text/html'
    doc = Oga.parse_html(file.read)
    find_stylesheets(doc, path).each { |file| request(file) }
    self.elements = find_elements(doc)
  else
    raise StyleStats::ContentError.new
  end
rescue SocketError, RuntimeError
  raise StyleStats::RequestError.new
end