class SvgoWrapper

Constants

DEFAULT_TIMEOUT
VALID_PLUGINS
VERSION

Attributes

disabled_plugins[R]
enabled_plugins[R]
plugin_args[RW]
timeout[R]

Public Class Methods

new(enable: nil, disable: nil, timeout: DEFAULT_TIMEOUT) click to toggle source
# File lib/svgo_wrapper.rb, line 14
def initialize(enable: nil, disable: nil, timeout: DEFAULT_TIMEOUT)
  self.enabled_plugins = enable
  self.disabled_plugins = disable
  self.plugin_args = generate_plugin_args(enabled: enabled_plugins, disabled: disabled_plugins)
  self.timeout = timeout
end
svgo_present?() click to toggle source
# File lib/svgo_wrapper/svgo_check.rb, line 6
def svgo_present?
  begin
    Open4.spawn "svgo -i - -o -",
                stdin: " <svg/>",
                stdout: output = "",
                stdout_timeout: 5
  rescue
    return false
  end

  output.start_with?("<svg")
end

Public Instance Methods

optimize_images_data(data) click to toggle source
# File lib/svgo_wrapper.rb, line 21
def optimize_images_data(data)
  begin
    Open4.spawn ["svgo", *plugin_args, "-i", "-", "-o", "-"],
                stdin: data,
                stdout: output = "",
                stdout_timeout: timeout
  rescue Open4::SpawnError => e
    raise Error, "Unexpected error (#{e.exitstatus})\n"
  end

  verify_output(output)
  output
end
timeout=(value) click to toggle source
# File lib/svgo_wrapper.rb, line 35
def timeout=(value)
  if value.is_a? Numeric
    @timeout = value
  elsif @timeout.nil?
    @timeout = DEFAULT_TIMEOUT
  end
end

Private Instance Methods

disabled_plugins=(values) click to toggle source
# File lib/svgo_wrapper.rb, line 47
def disabled_plugins=(values)
  @disabled_plugins = filter_plugins(Set[*values]).freeze
end
enabled_plugins=(values) click to toggle source
# File lib/svgo_wrapper.rb, line 51
def enabled_plugins=(values)
  @enabled_plugins = filter_plugins(Set[*values]).freeze
end
filter_plugins(plugins) click to toggle source
# File lib/svgo_wrapper.rb, line 55
def filter_plugins(plugins)
  VALID_PLUGINS & plugins.map(&:to_sym)
end
generate_plugin_args(enabled:, disabled:) click to toggle source
# File lib/svgo_wrapper.rb, line 59
def generate_plugin_args(enabled:, disabled:)
  (disabled.map {|v| "--disable=#{v}".freeze } +
   enabled.map {|v| "--enable=#{v}".freeze }).freeze
end
verify_output(output) click to toggle source
# File lib/svgo_wrapper.rb, line 64
def verify_output(output)
  return if output =~ /<svg/

  output = "There was a problem optimizing the SVG image with the selected plugins\n" if output.strip.empty?
  raise ParserError, output
end