Class: Imdhemy::Jekyll::Theme::ExternalOptimizer

Inherits:
Object
  • Object
show all
Defined in:
lib/imdhemy/jekyll/theme/image_cli.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(label:, command_builder:, temp_output_builder:) ⇒ ExternalOptimizer

Returns a new instance of ExternalOptimizer.



221
222
223
224
225
# File 'lib/imdhemy/jekyll/theme/image_cli.rb', line 221

def initialize(label:, command_builder:, temp_output_builder:)
  @label = label
  @command_builder = command_builder
  @temp_output_builder = temp_output_builder
end

Instance Attribute Details

#labelObject (readonly)

Returns the value of attribute label.



227
228
229
# File 'lib/imdhemy/jekyll/theme/image_cli.rb', line 227

def label
  @label
end

Instance Method Details

#optimize(path) ⇒ Object



229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
# File 'lib/imdhemy/jekyll/theme/image_cli.rb', line 229

def optimize(path)
  Dir.mktmpdir("imdhemy-image") do |tmpdir|
    temp_dir = Pathname(tmpdir)
    temp_output = @temp_output_builder.call(path, temp_dir)
    command = @command_builder.call(path, temp_output)

    success = system(*command, out: File::NULL, err: File::NULL)
    raise "Optimizer failed: #{Shellwords.join(command)}" unless success

    if !temp_output.exist? || temp_output.size >= path.size
      return { changed: false, message: "#{label} ran but produced no smaller output" }
    end

    FileUtils.cp(temp_output, path)
    { changed: true, message: label }
  end
end