0

I'm working on a multi-language project. I'm using I18n gem for localization purposes. In some point I want to pass an empty value like following:

current_locale("")

Where the current_locale() function is

def current_locale(locale)
    if locale.empty?
      translation = find_translation(locale)
    else 
      translation = find_translation( I18n.locale ) || find_translation( I18n.default_locale ) || translations.first
    end
    translation.locale  
  end

But when the current_locale() function is called, it gives me following error:

undefined method `locale' for nil:NilClass

Does anyone know how to fix this error?

Thanks

Mujahid
  • 1,227
  • 5
  • 32
  • 62
  • `find_translation(locale)` when locale is `""` returns `nil`. What is `find_translation` and what it should return on `""`? – Yevgeniy Anfilofyev Oct 10 '13 at 06:41
  • @YevgeniyAnfilofyev: Well its a function in `has_translations.rb` class in `I18n gem`. Following is the function `def find_translation(locale) locale = locale.to_s translations.detect { |t| t.locale == locale } end` – Mujahid Oct 10 '13 at 06:43
  • You see, in `find_translation` it converts locale to string and looks up for locale into `translations` enumerable and if doesn't find any -- returns `nil`. I guess it couldn't find anything for `""` locale. – Yevgeniy Anfilofyev Oct 10 '13 at 06:57
  • So any work around can you suggest me to pass an empty value to current_locale()? Thanks – Mujahid Oct 10 '13 at 07:06
  • 1
    I think you shouldn't pass `""` as a locale (and actually, you can't do it, as I see the code). Try to rethink your algorithm and find out how to avoid passing empty locale in this situation. – Yevgeniy Anfilofyev Oct 10 '13 at 07:11

1 Answers1

0

Change the two first lines and it should work (as long as you have at least in translation in translations).

def current_locale(locale = nil)
  if locale.blank?
    ...
spickermann
  • 100,941
  • 9
  • 101
  • 131
  • There are only two places in the code that can lead to a `nil` `translation`. First `find_translation(locale)` in line 3, but that would not be called if you check for `local.blank?` before. The second place is `translations.first`, if all other `find_translation` did not find anything. Therefore please double check if there is a `translation` in `translations.first`. – spickermann Oct 10 '13 at 06:46