awesome_hstore_translate
awesome_hstore_translate copied to clipboard
Fallback logic is incorrect with accessors
I believe fallback logic is incorrect:
Given
class Entity
translates :title, accessors: [:en, :es]
end
entity.title_en = "english"
entity.title_es = nil
Expected
I18n.locale = :en
entity.title
=> "english" # correct
I18n.locale = :es
entity.title
=> "english" # correct: fallback to default_locale
entity.title_en
=> "english"
entity.title_es
=> nil # should not fall back
Actual
entity.title_es
=> "english" # incorrect
I believe this is incorrect and accessors should provide the real data otherwise it is impossible to edit models. Also this is how it is implemented in globalize_accessors.
In other words they should provide direct mapping to title_raw, this is what I did:
module Translates
def translates(*args)
super(*args)
define_translated_accessors(*args)
end
private
def define_translated_accessors(*attrs)
attrs.each do |attr|
I18n.available_locales.each do |locale|
define_method "#{attr}_#{locale}=" do |value|
write_translated_attribute(attr, value, locale)
end
define_method "#{attr}_#{locale}" do
Hash(send("#{attr}_raw"))[locale.to_s]
end
end
end
end
end
Thank you Nick for providing this issue. I'll have a look into it soon!