-
Notifications
You must be signed in to change notification settings - Fork 18
/
Copy pathtranslation_keeper.rb
145 lines (116 loc) · 2.76 KB
/
translation_keeper.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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
module Multilang
class MultilangTranslationKeeper
attr_reader :model
attr_reader :attribute
attr_reader :translations
def initialize(model, attribute)
@model = model
@attribute = attribute
@translations = {}
load!
end
def value(locale = nil)
@translations.value(locale)
end
def current_or_any_value
@translations.current_or_any_value
end
def current_or_default_value
@translations.current_or_default_value
end
def to_s
raw_read(actual_locale)
end
def to_str(locale = nil)
locale ||= actual_locale
raw_read(locale)
end
def update(value)
if value.is_a?(Hash)
clear
value.each { |k, v| write(k, v) }
elsif value.is_a?(MultilangTranslationProxy)
update(value.translation.translations)
elsif value.is_a?(String)
write(actual_locale, value)
end
flush!
end
def [](locale)
read(locale)
end
def []=(locale, value)
write(locale, value)
flush!
end
def locales
@translations.locales
end
def empty?
@translations.empty?
end
private
def actual_locale
@translations.actual_locale
end
def write(locale, value)
@translations[locale.to_s] = value
end
def read(locale)
@translations.read(locale)
end
def raw_read(locale)
@translations[locale.to_s] || ''
end
def clear
@translations.clear
end
def load!
data = @model[@attribute]
data = data.blank? ? nil : data
@translations = data.is_a?(Hash) ? data : {}
class << translations
attr_accessor :multilang_keeper
def to_s
"#{current_or_any_value}"
end
def locales
self.keys.map(&:to_sym)
end
def read(locale)
MultilangTranslationProxy.new(self.multilang_keeper, locale)
end
def current_or_default_value
value.empty? ? value(default_locale) : value
end
def current_or_any_value
v = value
if v.empty?
reduced_locales = locales - [actual_locale]
reduced_locales.each do |locale|
v = value(locale)
return v unless v.empty?
end
else
return v
end
return ''
end
def value(locale = actual_locale)
read(locale)
end
def actual_locale
I18n.locale
end
def default_locale
I18n.default_locale
end
end
@translations.public_send("multilang_keeper=", self)
end
def flush!
@model.send("#{@attribute}_will_change!")
@model[@attribute] = @translations
end
end
end