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
|
# File 'lib/hstorly/active_record_extensions.rb', line 6
def hstore_translate(*args)
args.each do |attribute|
define_method attribute do
(self[attribute] || {})[I18n.locale.to_s] || ""
end
define_method "#{attribute}=" do |value|
if value.is_a?(Hash)
write_attribute attribute, value
elsif self[attribute].present?
write_attribute attribute, self[attribute].merge({I18n.locale => value })
value
else
write_attribute attribute, {I18n.locale => value }
value
end
end
define_method "#{attribute}_before_type_cast" do
self[attribute] || {}
end
module_eval do
serialize "#{attribute}", ActiveRecord::Coders::Hstore
end if defined?(ActiveRecord::Coders::Hstore)
I18n.available_locales.map(&:to_s).each do |locale|
define_method "#{attribute}_#{locale}" do
(self[attribute] || {})[locale] || ""
end
define_method "#{attribute}_#{locale}=" do |value|
if self[attribute].present?
write_attribute attribute, self[attribute].merge({locale => value })
else
write_attribute attribute, {locale => value }
end
end
end
end
end
|