lib/middleman-webp/converter.rb in middleman-webp-0.2.2 vs lib/middleman-webp/converter.rb in middleman-webp-0.2.3
- old
+ new
@@ -25,13 +25,17 @@
@builder.say_status(:webp, "Total conversion savings: #{number_to_human_size(savings)} (#{change_percentage(@original_size, @converted_size)})", :blue)
end
def convert_images(paths, &after_conversion)
paths.each do |p|
- dst = destination_path(p)
- exec_convert_tool(p, dst)
- yield File.new(p), File.new(dst)
+ begin
+ dst = destination_path(p)
+ exec_convert_tool(p, dst)
+ yield File.new(p), File.new(dst)
+ rescue
+ @builder.say_status :webp, "Converting #{p} failed", :red
+ end
end
end
def exec_convert_tool(src, dst)
system("#{tool_for(src)} #{@options.for(src)} -quiet #{src} -o #{dst}")
@@ -52,11 +56,13 @@
# Calculate change percentage of converted file size
#
# src - File instance of the source
# dst - File instance of the destination
def change_percentage(src_size, dst_size)
- "%g %%" % ("%.2f" % [100 - 100.0 * dst_size / src_size])
+ return '0 %' if src_size == 0
+
+ format('%g %%', format('%.2f', 100 - 100.0 * dst_size / src_size))
end
def destination_path(src_path)
dst_name = src_path.basename.to_s.gsub(/(jpe?g|png|tiff?|gif)$/, "webp")
src_path.parent.join(dst_name)
@@ -66,12 +72,15 @@
all = ::Middleman::Util.all_files_under(@app.inst.build_dir)
all.select {|p| p.to_s =~ /(jpe?g|png|tiff?|gif)$/i }
end
def number_to_human_size(n)
+ return '0 B' if n == 0
+
units = %w{B KiB MiB GiB TiB PiB}
exponent = (Math.log(n) / Math.log(1024)).to_i
- "%g #{units[exponent]}" % ("%.2f" % (n.to_f / 1024**exponent))
+ format("%g #{units[exponent]}",
+ format('%.2f', n.to_f / 1024**exponent))
end
end
end
end