Forum: Rails I18n idea I18n.t(:not_existing).presence == nil

Posted by iain hecker (Guest)
on 2010-04-16 15:15
(Received via mailing list)
Hi guys,

I had an idea, just wondering what your thoughts on it are.

Short introduction: ActiveSupport 3 introduces the #presence method,
which returns nil if #present? returns false, otherwise it returns
self.

Can we define a singleton method on the strings that are returned when
the translation is not found?

Like this:

>> foo = I18n.t(:foo)
=> "translation missing: en, foo"
>> foo.present?
=> false
>> foo.blank?
=> true
>> foo.presence
=> nil

So, although it is a string (of some sort), it reacts as if its an
empty string, since there is no translation.

I know this is kinda counter-intuative, but it allows you to write:

>> I18n.t(:foo).presence || I18n.t(:hello)
=> "World"

Implementation wise, we could define some extra methods on this string
object, or we could make a MissingTranslation class that inherits from
String.

So, what are your opinions on this? Does anyone know of a gem that
already does something like this?

Cheers,
Iain Hecker
@iain_nl / github.com/iain / http://iain.nl
Posted by Krzysztof Knapik (Guest)
on 2010-04-16 15:30
(Received via mailing list)
Hi Iain,

By default I18n.translate returns *"translation missing"* string when
translation is missing, so the *present?* method always return true on 
that.
This is default behaviour, which is fine.

You can do it another way - by defining exception handler returning
nil on missing translation,
if you really need it:

   def your_exception_handler(exception, locale, key, options)
     if MissingTranslationData === exception
       # return exception.message
       return nil
     end
     raise exception
   end

I18n.exception_handler = :your_exception_handler

Also, for such cases

>>> I18n.t(:foo).presence || I18n.t(:hello)
> => "World"

you can always use default option I18n.t(:foo, :defult => 
I18n.t(:hello))

Regards,
KK

2010/4/16 iain hecker <iain@iain.nl>:
>
>
> String.
>
> So, what are your opinions on this? Does anyone know of a gem that
> already does something like this?
>
> Cheers,
> Iain Hecker
> @iain_nl / github.com/iain / http://iain.nl
>
> --
> You received this message because you are subscribed to the Google Groups
"rails-i18n" group.
> To post to this group, send email to rails-i18n@googlegroups.com.
> To unsubscribe from this group, send email to
rails-i18n+unsubscribe@googlegroups.com<rails-i18n%2Bunsubscribe@googlegroups.com>
.
> For more options, visit this group at
http://groups.google.com/group/rails-i18n?hl=en.
Please log in before posting. Registration is free and takes only a minute.
Existing account (Switch to SSL-encrypted connection)
NEW: Do you have a Google/GoogleMail or Yahoo account? No registration required!
Log in with Google account | Log in with Yahoo account
No account? Register here.