Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fallback logic is incorrect with accessors #8

Open
firedev opened this issue Feb 27, 2017 · 1 comment
Open

Fallback logic is incorrect with accessors #8

firedev opened this issue Feb 27, 2017 · 1 comment

Comments

@firedev
Copy link

firedev commented Feb 27, 2017

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 firedev changed the title Fallback logic is incorrect with accessorts Fallback logic is incorrect with accessors Feb 27, 2017
@openscript
Copy link
Owner

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants