Skip to content

Instantly share code, notes, and snippets.

@RStankov
Created October 9, 2010 21:14
Show Gist options
  • Save RStankov/618608 to your computer and use it in GitHub Desktop.
Save RStankov/618608 to your computer and use it in GitHub Desktop.
namespace :svg2js do
%w(object array).each do |format|
desc "convert svg files to javascript #{format}, require :from and :to arguments"
task format do
unless ENV["from"] && ENV["to"]
puts "from and to params required"
else
Svg2JsConvertor.convert(ENV["from"], ENV["to"], format)
puts "#{ENV["to"]} generated succesfully"
end
end
end
end
class Svg2JsConvertor
def self.convert(from_file, to_file, format)
convertor = self.new
convertor.load_file(from_file)
File.open(to_file, 'w+') do |file|
file.write convertor.__send__(:"to_js_#{format}")
end
end
PATTERN = /\W+d=("[^"]+")/
def initialize
@content = []
end
def load_file(file_name)
open(file_name) do |file|
file.each do |line|
if match = line.match(PATTERN)
@content << match[1]
end
end
end
end
def to_js_object
index = 0
pad = @content.size.to_s.size
"{\n " + @content.map { |line| "\"label#{(index += 1).to_s.rjust(pad, '0')}\": #{line}" }.join("\n , ") + "\n};"
end
def to_js_array
"[\n " + @content.join("\n, ") + "\n];"
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment