i18n-js 4.0.1 → 4.2.0

Sign up to get free protection for your applications and to get access to all the features.
@@ -0,0 +1,97 @@
1
+ # frozen_string_literal: true
2
+
3
+ module I18nJS
4
+ require "i18n-js/plugin"
5
+
6
+ class ExportFilesPlugin < I18nJS::Plugin
7
+ CONFIG_KEY = :export_files
8
+
9
+ def self.setup
10
+ I18nJS::Schema.root_keys << CONFIG_KEY
11
+ end
12
+
13
+ def self.validate_schema(config:)
14
+ return unless config.key?(CONFIG_KEY)
15
+
16
+ plugin_config = config[CONFIG_KEY]
17
+ valid_keys = %i[enabled files]
18
+ schema = I18nJS::Schema.new(config)
19
+
20
+ schema.expect_required_keys(valid_keys, plugin_config)
21
+ schema.reject_extraneous_keys(valid_keys, plugin_config)
22
+ schema.expect_enabled_config(CONFIG_KEY, plugin_config[:enabled])
23
+ schema.expect_array_with_items(:files, plugin_config[:files])
24
+
25
+ plugin_config[:files].each do |exports|
26
+ schema.expect_required_keys(%i[template output], exports)
27
+ schema.reject_extraneous_keys(%i[template output], exports)
28
+ schema.expect_type(:template, exports[:template], String, exports)
29
+ schema.expect_type(:output, exports[:output], String, exports)
30
+ end
31
+ end
32
+
33
+ def self.after_export(files:, config:)
34
+ return unless config.dig(CONFIG_KEY, :enabled)
35
+
36
+ exports = config.dig(CONFIG_KEY, :files)
37
+
38
+ require "erb"
39
+ require "digest/md5"
40
+ require "json"
41
+
42
+ files.each do |file|
43
+ dir = File.dirname(file)
44
+ name = File.basename(file)
45
+ extension = File.extname(name)
46
+ base_name = File.basename(file, extension)
47
+
48
+ exports.each do |export|
49
+ translations = JSON.load_file(file)
50
+ template = Template.new(
51
+ file: file,
52
+ translations: translations,
53
+ template: export[:template]
54
+ )
55
+
56
+ contents = template.render
57
+
58
+ output = format(
59
+ export[:output],
60
+ dir: dir,
61
+ name: name,
62
+ extension: extension,
63
+ digest: Digest::MD5.hexdigest(contents),
64
+ base_name: base_name
65
+ )
66
+
67
+ File.open(output, "w") do |io|
68
+ io << contents
69
+ end
70
+ end
71
+ end
72
+ end
73
+
74
+ class Template
75
+ attr_accessor :file, :translations, :template
76
+
77
+ def initialize(**kwargs)
78
+ kwargs.each do |key, value|
79
+ public_send("#{key}=", value)
80
+ end
81
+ end
82
+
83
+ def banner(comment: "// ", include_time: true)
84
+ [
85
+ "#{comment}File generated by i18n-js",
86
+ include_time ? " on #{Time.now}" : nil
87
+ ].compact.join
88
+ end
89
+
90
+ def render
91
+ ERB.new(File.read(template)).result(binding)
92
+ end
93
+ end
94
+ end
95
+
96
+ I18nJS.register_plugin(ExportFilesPlugin)
97
+ end