Class: RailsCriticalCss::Extractor

Inherits:
Object
  • Object
show all
Includes:
Actions::Helpers
Defined in:
lib/rails_critical_css/extractor.rb

Class Method Summary collapse

Instance Method Summary collapse

Methods included from Actions::Helpers

#absolute_asset_file_path, #eval_option, #eval_options, #gen_critical_css_cache_path, #group_assets_by_type

Constructor Details

#initialize(options) ⇒ Extractor

Returns a new instance of Extractor.



12
13
14
# File 'lib/rails_critical_css/extractor.rb', line 12

def initialize(options)
  @html, @css = options.values_at(:html, :css)
end

Class Method Details

.extractor_process_input(html_path:, css_path:) ⇒ Object



46
47
48
49
50
51
52
53
# File 'lib/rails_critical_css/extractor.rb', line 46

def self.extractor_process_input(html_path:, css_path:)
  config = ::RailsCriticalCss::Config.as_json_config({
    url: "file://#{html_path}",
    css: css_path,
  })

  JSON.generate(config)
end

Instance Method Details

#try_extractObject



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
# File 'lib/rails_critical_css/extractor.rb', line 16

def try_extract
  tmp_html_file = tmp_extractor_file(@html, extension: 'html')
  tmp_css_file = tmp_concat_assets_array(@css[:assets], extension: 'css')
  return nil unless tmp_html_file.present? && tmp_css_file.present?

  stdout, stderr = Dir.chdir(LIB_ROOT) do
    Open3.capture2e(
      'node js/css-extractor.js',
      stdin_data: Extractor.extractor_process_input(
        html_path: tmp_html_file.path,
        css_path: tmp_css_file.path,
      )
    )
  end

  if stderr.try(:success?) && !stdout.try(:include?, 'UnhandledPromiseRejectionWarning')
    [
      extract_critical_assets(@css[:assets]),
      stdout.try(:gsub, /src:[^;]+;/, ''),
    ].join(' ')
  else
    nil
  end
rescue
  nil
ensure
  tmp_html_file&.delete
  tmp_css_file&.delete
end