# encoding: utf-8 require "zh/version" path = File.expand_path(File.dirname(__FILE__)) $:.unshift(path) unless $:.include?(path) require 'open-uri' require 'json' class Zh class << self LOCALE = [:cn, :sg, :tw, :hk] # sg, cn 是簡體,tw, hk 是繁體 LOCALE.each do |method| define_method "to_#{method}" do |message| converter(method, message) end end def converter(method, message) if method == :tw || method == :hk localize_json = file_parser(method) localize_json.each_key { |k| message.gsub!(k, localize_json[k]) } traditionalize_json = file_parser("hant") traditionalize_json.each_key { |k| message.gsub!(k, traditionalize_json[k]) } elsif method == :cn || method == :sg localize_json = file_parser(method) localize_json.each_key { |k| message.gsub!(k, localize_json[k]) } simplify_json = file_parser("hans") simplify_json.each_key { |k| message.gsub!(k, simplify_json[k]) } end message end def update_data variants = [:cn, :sg, :tw, :hk, :hans, :hant] variants.each do |l| json = file_parser(l) url = "http://zh.wikipedia.org/w/index.php?title=MediaWiki:Conversiontable/zh-#{l}&action=raw&templates=expand" table = open(url).read table.lines do |line| matches = line.match(/^[\*\"]([^\"=]+)\"?\s*=>\s*\"?([^\s\/\"]+)\s?.*\"?[;,]$/) if matches json[matches[1].strip] = matches[2].strip end end write_to_json(l, json) end true end private def file_parser(locale) file = File.read(File.expand_path(File.dirname(__FILE__)) + "/../data/zh-#{locale}.json") json = JSON.parse(file) end def write_to_json(l, j) json = j begin file = File.open(File.expand_path(File.dirname(__FILE__)) + "/../data/zh-#{l}.json", "w") file.write(json.to_json) rescue IOError => e puts "An error occurred: #{$!}" ensure file.close unless file == nil end end end end