Class: SvgOptimizer

Inherits:
Object
  • Object
show all
Defined in:
lib/svgo.rb

Instance Method Summary collapse

Constructor Details

#initialize(options = SvgoOptions.new) {|options| ... } ⇒ SvgOptimizer

Returns a new instance of SvgOptimizer.

Yields:

  • (options)


113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
# File 'lib/svgo.rb', line 113

def initialize(options=SvgoOptions.new)
    yield options if block_given?
    if options.is_a? SvgoOptions
        @options = options.get_options
    else
        @options = options
    end

    runtime = @options.delete "runtime"
    unless runtime
        # therubyracer is a first choice for execjs but its libv8 is too
        # old for the svgo library and its dependencies.
        runtimes = [
            # MacOS only system component
            ExecJS::Runtimes::JavaScriptCore,
            ExecJS::Runtimes::MiniRacer,
            ExecJS::Runtimes::Node
        ]
        runtime = runtimes.select {|r| r.available?}.first
        unless runtime
            raise ExecJS::RuntimeUnavailable.new(
                "No supported runtime available please install " \
                "`mini_racer` or `NodeJS`."
            )
        end
    end
    ExecJS.runtime = runtime
    if not @options[:plugins]
        @options[:plugins] = PLUGINS_DEFAULT
    end
    if @options[:plugins].is_a? Array
        @options[:plugins] = @options[:plugins].map {|p| [p, true]}.to_h
    end
    svgo_js = File.expand_path("../../svgo-js/svgo-built.js", __FILE__)
    svgo_module = File.open(svgo_js, "r:utf-8", &:read)
    @context = ExecJS.compile(svgo_module)
end

Instance Method Details

#optimize(svg_data) ⇒ Object



151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
# File 'lib/svgo.rb', line 151

def optimize(svg_data)
    result = @context.call("svgo", @options.to_json, svg_data.to_s)
    if not result
        raise StandardError.new("Bad response from JavaScript runtime.")
    end
    if result['errors'].length > 0
        if result['errors'].length > 1
            err = %Q(Errors occurred: \n - #{result['errors'].join("\n - s")})
        else
            err = "An error occurred: #{result['errors'][0]}"
        end
        raise StandardError.new(err)
    end
    result
end

#optimize_file(svg_file) ⇒ Object



167
168
169
# File 'lib/svgo.rb', line 167

def optimize_file(svg_file)
    optimize(File.read(svg_file))
end