Class: CriticalPathCss::CssFetcher

Inherits:
Object
  • Object
show all
Defined in:
lib/critical_path_css/css_fetcher.rb

Constant Summary collapse

GEM_ROOT =
File.expand_path(File.join('..', '..'), File.dirname(__FILE__))

Instance Method Summary collapse

Constructor Details

#initialize(config) ⇒ CssFetcher

Returns a new instance of CssFetcher.



8
9
10
# File 'lib/critical_path_css/css_fetcher.rb', line 8

def initialize(config)
  @config = config
end

Instance Method Details

#fetchObject



12
13
14
# File 'lib/critical_path_css/css_fetcher.rb', line 12

def fetch
  @config.routes.map { |route| [route, fetch_route(route)] }.to_h
end

#fetch_route(route) ⇒ Object



16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
# File 'lib/critical_path_css/css_fetcher.rb', line 16

def fetch_route(route)
  options = {
    'url' => @config.base_url + route,
    'css' => @config.path_for_route(route),
    'width' => 1300,
    'height' => 900,
    'timeout' => 30_000,
    # CSS selectors to always include, e.g.:
    'forceInclude' => [
      #  '.keepMeEvenIfNotSeenInDom',
      #  '^\.regexWorksToo'
    ],
    # set to true to throw on CSS errors (will run faster if no errors)
    'strict' => false,
    # characters; strip out inline base64 encoded resources larger than this
    'maxEmbeddedBase64Length' => 1000,
    # specify which user agent string when loading the page
    'userAgent' => 'Penthouse Critical Path CSS Generator',
    # ms; render wait timeout before CSS processing starts (default: 100)
    'renderWaitTime' => 100,
    # set to false to load (external) JS (default: true)
    'blockJSRequests' => true,
    'customPageHeaders' => {
      # use if getting compression errors like 'Data corrupted':
      'Accept-Encoding' => 'identity'
    }
  }.merge(@config.penthouse_options)
  out, err, st = Dir.chdir(GEM_ROOT) do
    Open3.capture3('node', 'lib/fetch-css.js', JSON.dump(options))
  end
  if !st.exitstatus.zero? || out.empty? && !err.empty?
    STDOUT.puts out
    STDERR.puts err
    STDERR.puts "Failed to get CSS for route #{route}\n" \
          "  with options=#{options.inspect}"
  end
  out
end