awesome_hstore_translate icon indicating copy to clipboard operation
awesome_hstore_translate copied to clipboard

Fallback logic is incorrect with accessors

Open firedev opened this issue 8 years ago • 1 comments

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

firedev avatar Feb 27 '17 10:02 firedev

Thank you Nick for providing this issue. I'll have a look into it soon!

openscript avatar Feb 28 '17 07:02 openscript