Module: Klenod::Build::AssetCompression

Defined in:
lib/klenod/build/asset_compression.rb

Constant Summary collapse

TEXT_CONTENT_TYPES =
[
  "application/javascript",
  "application/json",
  "application/manifest+json",
  "application/rss+xml",
  "application/xml",
  "image/svg+xml"
].freeze

Class Method Summary collapse

Class Method Details

.compressible?(asset) ⇒ Boolean

Returns:

  • (Boolean)


18
19
20
21
# File 'lib/klenod/build/asset_compression.rb', line 18

def self.compressible?(asset)
  content_type = asset.content_type.to_s.split(";", 2).first
  content_type.start_with?("text/") || TEXT_CONTENT_TYPES.include?(content_type)
end

.remove_sidecar(path) ⇒ Object



41
42
43
44
45
# File 'lib/klenod/build/asset_compression.rb', line 41

def self.remove_sidecar(path)
  brotli_path = sidecar_path(path)
  FileUtils.rm_f(brotli_path)
  brotli_path
end

.sidecar_path(path) ⇒ Object



23
24
25
# File 'lib/klenod/build/asset_compression.rb', line 23

def self.sidecar_path(path)
  "#{path}.br"
end

.write_atomic(path, bytes) ⇒ Object



47
48
49
50
51
52
53
54
55
# File 'lib/klenod/build/asset_compression.rb', line 47

def self.write_atomic(path, bytes)
  temp_path = "#{path}.tmp.#{$$}.#{object_id}"
  FileUtils.mkdir_p(File.dirname(path))
  File.binwrite(temp_path, bytes)
  File.rename(temp_path, path)
rescue
  FileUtils.rm_f(temp_path) if temp_path
  raise
end

.write_sidecar(asset, path) ⇒ Object



27
28
29
30
31
32
33
34
35
36
37
38
39
# File 'lib/klenod/build/asset_compression.rb', line 27

def self.write_sidecar(asset, path)
  return nil unless compressible?(asset)

  brotli_path = sidecar_path(path)
  return :skipped if File.file?(brotli_path)

  bytes = asset.bytes
  compressed = Brotli.deflate(bytes, quality: 11, mode: :text)
  return nil unless compressed.bytesize < bytes.bytesize

  write_atomic(brotli_path, compressed)
  :written
end