i18n-js 4.0.0 → 4.2.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,103 @@
1
+ # frozen_string_literal: true
2
+
3
+ module I18nJS
4
+ require "i18n-js/plugin"
5
+
6
+ class ExportFilesPlugin < I18nJS::Plugin
7
+ def setup
8
+ I18nJS::Schema.root_keys << config_key
9
+ end
10
+
11
+ def validate_schema
12
+ valid_keys = %i[enabled files]
13
+
14
+ schema.expect_required_keys(keys: valid_keys, path: [config_key])
15
+ schema.reject_extraneous_keys(keys: valid_keys, path: [config_key])
16
+ schema.expect_array_with_items(path: [config_key, :files])
17
+
18
+ config[:files].each_with_index do |_exports, index|
19
+ export_keys = %i[template output]
20
+
21
+ schema.expect_required_keys(
22
+ keys: export_keys,
23
+ path: [config_key, :files, index]
24
+ )
25
+
26
+ schema.reject_extraneous_keys(
27
+ keys: export_keys,
28
+ path: [config_key, :files, index]
29
+ )
30
+
31
+ schema.expect_type(
32
+ path: [config_key, :files, index, :template],
33
+ types: String
34
+ )
35
+
36
+ schema.expect_type(
37
+ path: [config_key, :files, index, :output],
38
+ types: String
39
+ )
40
+ end
41
+ end
42
+
43
+ def after_export(files:)
44
+ require "erb"
45
+ require "digest/md5"
46
+ require "json"
47
+
48
+ files.each do |file|
49
+ dir = File.dirname(file)
50
+ name = File.basename(file)
51
+ extension = File.extname(name)
52
+ base_name = File.basename(file, extension)
53
+
54
+ config[:files].each do |export|
55
+ translations = JSON.load_file(file)
56
+ template = Template.new(
57
+ file: file,
58
+ translations: translations,
59
+ template: export[:template]
60
+ )
61
+
62
+ contents = template.render
63
+
64
+ output = format(
65
+ export[:output],
66
+ dir: dir,
67
+ name: name,
68
+ extension: extension,
69
+ digest: Digest::MD5.hexdigest(contents),
70
+ base_name: base_name
71
+ )
72
+
73
+ File.open(output, "w") do |io|
74
+ io << contents
75
+ end
76
+ end
77
+ end
78
+ end
79
+
80
+ class Template
81
+ attr_accessor :file, :translations, :template
82
+
83
+ def initialize(**kwargs)
84
+ kwargs.each do |key, value|
85
+ public_send("#{key}=", value)
86
+ end
87
+ end
88
+
89
+ def banner(comment: "// ", include_time: true)
90
+ [
91
+ "#{comment}File generated by i18n-js",
92
+ include_time ? " on #{Time.now}" : nil
93
+ ].compact.join
94
+ end
95
+
96
+ def render
97
+ ERB.new(File.read(template)).result(binding)
98
+ end
99
+ end
100
+ end
101
+
102
+ I18nJS.register_plugin(ExportFilesPlugin)
103
+ end