Class: Rails::WebP::Converter

Inherits:
Object
  • Object
show all
Defined in:
lib/rails/webp/converter.rb

Class Attribute Summary collapse

Class Method Summary collapse

Class Attribute Details

.contextObject (readonly)

Returns the value of attribute context.



9
10
11
# File 'lib/rails/webp/converter.rb', line 9

def context
  @context
end

Class Method Details

.convert_to_webp(input_path, output_path) ⇒ Object



11
12
13
14
15
16
17
18
19
20
21
22
# File 'lib/rails/webp/converter.rb', line 11

def convert_to_webp(input_path, output_path)
  # Ex: convert wizard.png -quality 50 -define webp:lossless=true wizard.webp
  MiniMagick::Tool::Convert.new do |convert|
    convert << input_path
    options = WebP.encode_options
    convert << '-quality' << options[:quality]
    options.except(:quality).each do |name, value|
      convert << "-define" << "webp:#{name.to_s.dasherize}=#{value}"
    end
    convert << output_path
  end
end

.process(input_path, data, context, app = Rails.application) ⇒ Object



24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
# File 'lib/rails/webp/converter.rb', line 24

def process(input_path, data, context, app = Rails.application)
  return data if excluded_dir?(input_path)
  @context = context
  prefix = app.config.assets.prefix
  digest = data_digest(data)
  webp_file = webp_file_name(data, digest)
  output_path = Pathname.new(File.join(app.root, 'public', prefix, webp_file))
  if WebP.force || !webp_file_exists?(digest, output_path)
    FileUtils.mkdir_p(output_path.dirname) unless Dir.exists?(output_path.dirname)
    # TODO: check app.assets.gzip and act accordingly
    convert_to_webp(input_path, output_path)
    logger&.info "Writing #{output_path}"
  end
  data
end