Module: Optipng

Defined in:
lib/optipng.rb

Overview

The optipng tool command frontend.

Defined Under Namespace

Classes: Result

Constant Summary collapse

COMMAND =

Holds optipng command.

:optipng
MATCHERS =

Holds output matchers.

[
    /^Processing\:\s*(.*)/,
    /^Error:\s*(.*)/,
    /(\d+\.\d+)%/,
    /already optimized\.$/,
]

Class Method Summary collapse

Class Method Details

.available?Boolean

Checks if jpegoptim is available.

Returns:

  • (Boolean)

    true if it is, false in otherwise



42
43
44
# File 'lib/optipng.rb', line 42

def self.available?
    return Whereis.available? self::COMMAND 
end

.optimize(paths, options = { }, &block) ⇒ Struct

Performs optimizations above file or set of files.

If block is given, runs optipng asynchronously. In that case, em-pipe-run file must be already required.

Parameters:

  • paths (String, Array)

    file path or array of paths for optimizing

  • options (Hash) (defaults to: { })

    options

  • block (Proc)

    block for giving back the results

Options Hash (options):

  • :level (Integer)

    optimization level (0-7)

  • :debug (Boolean)

    turn on debugging mode, so command will be put out to the STDERR

Returns:



60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
# File 'lib/optipng.rb', line 60

def self.optimize(paths, options = { }, &block)

    # Command
    cmd = CommandBuilder::new(self::COMMAND)
    
    # Max
    if options[:level].kind_of? Integer
        cmd.arg(:o, options[:level].to_i)
    end
    
    # Files
    if paths.kind_of? String
        paths = [paths]
    end
    
    # Runs the command
    cmd << paths
    
    if options[:debug] == true
        STDERR.write cmd.to_s + "\n"
    end
        
        # Blocking
        if block.nil?
            output = cmd.execute!

            # Parses output
            succeed, errors = __parse_output(output)
            return self::Result::new(succeed, errors)
            
        # Non-blocking
        else
            cmd.execute do |output|
                succeed, errors = __parse_output(output)
                block.call(self::Result::new(succeed, errors))
            end
        end
    
end