# frozen_string_literal: true require 'zh/version' require 'open-uri' require 'yajl/json_gem' class Zh class Error < StandardError; end class << self RB_LT_25 = Gem::Version.new(RUBY_VERSION) < Gem::Version.new('2.5.0') TRADITIONAL_LOCALE = %i[tw hk].freeze SIMPLIFIED_LOCALE = %i[cn sg].freeze LOCALE = TRADITIONAL_LOCALE + SIMPLIFIED_LOCALE # sg, cn are Simplified Chinese, tw, hk are Traditional Chinese LOCALE.each do |method| define_method "to_#{method}" do |message| converter(method, message) end end def converter(method, message) default_locale_data = locale_data(method) default_locale_data.each_key { |k| message.gsub!(k, default_locale_data[k]) } hanx_data = locale_data(TRADITIONAL_LOCALE.include?(method) ? 'hant' : 'hans') hanx_data.each_key { |k| message.gsub!(k, hanx_data[k]) } message end def update_data %i[cn sg tw hk hans hant].each do |locale| data = locale_data(locale) url = "https://zh.wikipedia.org/w/index.php?title=MediaWiki:Conversiontable/zh-#{locale}&action=raw&templates=expand" table = RB_LT_25 ? open(url).read : URI.open(url).read table.lines do |line| matches = line.match(%r{^[*"]([^"=]+)"?\s*=>\s*"?([^\s/"]+)\s?.*"?[;,]$}) data[matches[1].strip] = matches[2].strip if matches end write_to_json(locale, data) end true end private def locale_data(locale) json = File.new(__dir__ + "/data/zh-#{locale}.json", 'r') parser = Yajl::Parser.new parser.parse(json) end def write_to_json(locale, data) file = File.open(__dir__ + "/data/zh-#{locale}.json", 'w') file.write(data.to_json) rescue IOError => e puts "An error occurred: #{$ERROR_INFO}" ensure file&.close end end end