Class: SvgOptimizer

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

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

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

Returns a new instance of SvgOptimizer.

Yields:



115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
# File 'lib/svgo.rb', line 115

def initialize(options=SvgoOptions.new)
    yield options if block_given?
    if options.is_a? SvgoOptions
        @options = options.get_options
    else
        @options = options
    end
    if not @options[:plugins]
        @options[:plugins] = PLUGINS_DEFAULT
    end
    if not @options[:plugins].is_a? Array
        raise StandardError.new("`options.plugins` should be an Array.")
    end
    @options[:plugins] = @options[:plugins].map { | p |
      p.is_a?(Hash) ? p : {p => true}
    }
    svgo_js = File.expand_path("../../svgo-js/svgo-built.js", __FILE__)
    svgo_module = File.open(svgo_js, "r:utf-8", &:read)
    @context = MiniRacer::Context.new
    @context.eval svgo_module
    @context.call("svgo", {setup: @options})
end

Instance Attribute Details

#optionsObject

Returns the value of attribute options.



114
115
116
# File 'lib/svgo.rb', line 114

def options
  @options
end

Instance Method Details

#optimize(svg_data) ⇒ Object



138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
# File 'lib/svgo.rb', line 138

def optimize(svg_data)
    result = @context.call("svgo", {optimize: 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



154
155
156
# File 'lib/svgo.rb', line 154

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