Class: SvgOptimizer
- Inherits:
-
Object
- Object
- SvgOptimizer
- Defined in:
- lib/svgo.rb
Instance Method Summary collapse
-
#initialize(options = SvgoOptions.new) {|options| ... } ⇒ SvgOptimizer
constructor
A new instance of SvgOptimizer.
- #optimize(svg_data) ⇒ Object
- #optimize_file(svg_file) ⇒ Object
Constructor Details
#initialize(options = SvgoOptions.new) {|options| ... } ⇒ SvgOptimizer
Returns a new instance of SvgOptimizer.
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(=SvgoOptions.new) yield if block_given? if .is_a? SvgoOptions @options = . else @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.("../../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 |