|
1 | | -require 'yaml' |
2 | | -require 'singleton' |
| 1 | +# frozen_string_literal: true |
3 | 2 |
|
4 | | -class Interscript |
5 | | - include Singleton |
6 | | - |
7 | | - SYSTEM_DEFINITIONS_PATH = File.expand_path('../../maps', __FILE__) |
| 3 | +require 'yaml' |
8 | 4 |
|
9 | | - def initialize |
10 | | - @systems = {} |
11 | | - end |
| 5 | +# Transliteration |
| 6 | +module Interscript |
| 7 | + SYSTEM_DEFINITIONS_PATH = File.expand_path('../maps', __dir__) |
12 | 8 |
|
13 | | - def transliterate_file(system_code, input_file, output_file) |
14 | | - input = File.read(input_file) |
15 | | - output = transliterate(system_code, input) |
| 9 | + class << self |
| 10 | + def transliterate_file(system_code, input_file, output_file) |
| 11 | + input = File.read(input_file) |
| 12 | + output = transliterate(system_code, input) |
16 | 13 |
|
17 | | - File.open(output_file, "w") do |f| |
18 | | - f.puts(output) |
| 14 | + File.open(output_file, "w") do |f| |
| 15 | + f.puts(output) |
| 16 | + end |
| 17 | + puts "Output written to: #{output_file}" |
19 | 18 | end |
20 | | - puts "Output written to: #{output_file}" |
21 | | - end |
22 | | - |
23 | | - def load_system_definition(system_code) |
24 | | - @systems[system_code] ||= YAML.load_file(File.join(SYSTEM_DEFINITIONS_PATH, "#{system_code}.yaml")) |
25 | | - end |
26 | | - |
27 | | - def get_system(system_code) |
28 | | - @systems[system_code] |
29 | | - end |
30 | 19 |
|
31 | | - def system_char_map(system_code) |
32 | | - get_system(system_code)["map"]["characters"] |
33 | | - end |
34 | | - |
35 | | - def system_rules(system_code) |
36 | | - get_system(system_code)["map"]["rules"] |
37 | | - end |
| 20 | + def load_system_definition(system_code) |
| 21 | + YAML.load_file(File.join(SYSTEM_DEFINITIONS_PATH, "#{system_code}.yaml")) |
| 22 | + end |
38 | 23 |
|
39 | | - def transliterate(system_code, string) |
40 | | - load_system_definition(system_code) |
| 24 | + def transliterate(system_code, string) |
| 25 | + system = load_system_definition(system_code) |
41 | 26 |
|
42 | | - # TODO: also need to support regular expressions via system_rules(system_code), before system_char_map |
| 27 | + rules = system["map"]["rules"] || [] |
| 28 | + charmap = system["map"]["characters"] || {} |
43 | 29 |
|
44 | | - character_map = system_char_map(system_code) |
| 30 | + rules.each do |r| |
| 31 | + string.gsub! %r{#{r["pattern"]}}, r["result"] |
| 32 | + end |
45 | 33 |
|
46 | | - string.split('').map do |char| |
47 | | - converted_char = character_map[char] ? character_map[char] : char |
48 | | - string[char] = converted_char |
49 | | - end.join('') |
| 34 | + string.split('').map do |char| |
| 35 | + charmap[char] || char |
| 36 | + end.join('') |
| 37 | + end |
50 | 38 | end |
51 | | - |
52 | 39 | end |
53 | | - |
0 commit comments