-
Notifications
You must be signed in to change notification settings - Fork 8
/
value_range_to_wording.rb
69 lines (62 loc) · 2.54 KB
/
value_range_to_wording.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
module AdLocalize
module Mappers
class ValueRangeToWording
def map(value_range:)
values = value_range.values
analyze_header(first_row: values.first)
return unless valid_header?
translations = map_rows(values: values)
locale_wordings = translations.group_by(&:locale).map do |locale, group|
Entities::LocaleWording.new(locale: locale, translations: group)
end
Entities::Wording.new(locale_wordings: locale_wordings, default_locale: @locale_mapping.keys.first)
end
private
def map_rows(values:)
translations = []
values[1..-1].each do |row|
row_translations = map_row(row: row)
next if row_translations.blank?
existing_keys = translations.map(&:key)
new_translations = row_translations.reject do |translation|
existing_keys.any? do |key|
existing_plural_key = key.label == translation.key.label && key.plural? && translation.key.singular?
key.same_as?(key: translation.key) || existing_plural_key
end
end
translations.concat(new_translations)
end
translations
end
def analyze_header(first_row:)
@header = first_row
@key_index = first_row.index(Constant::CSV_WORDING_KEYS_COLUMN)
@locale_mapping = {}
first_row[@key_index.succ..-1].each_index do |relative_index|
absolute_index = @key_index.succ + relative_index
next if first_row[absolute_index].blank? || first_row[absolute_index].include?(Constant::COMMENT_KEY_COLUMN_IDENTIFIER)
@locale_mapping[first_row[absolute_index]] = { key_index: absolute_index }
comment_column_name = "#{Constant::COMMENT_KEY_COLUMN_IDENTIFIER} #{first_row[absolute_index]}"
@locale_mapping[first_row[absolute_index]][:comment_index] = first_row.index(comment_column_name)
end
end
def map_row(row:)
csv_wording_key = row[@key_index]
return if csv_wording_key.blank?
key = Entities::Key.new(label: csv_wording_key)
@locale_mapping.map do |locale, index_mapping|
comment = index_mapping[:comment_index].nil? ? nil : row[index_mapping[:comment_index]]
Entities::Translation.new(
locale: locale,
key: key,
value: row[index_mapping[:key_index]],
comment: comment
)
end
end
def valid_header?
@key_index.present? || @locale_mapping.keys.size.positive?
end
end
end
end