rails 3, user-specific localization: sending SMS messages in a user's preferred language
when our app sends SMS messages, we'd like to give开发者_运维技巧 users the option to specify their preferred language.
Using Spanish as an example, I see how to add a new locale yml file to config/locales.
And I see how to replace any hardcoded strings such as "text STOP to opt-out" with :stop_opt_out in my app.
what I don't see is how to select the language used on a user-by-user basis.
specifically if my code is currently:
msg_out = "Thank you!"
and after internationalization I have :thank_you
defined in multiple locale yml files
and if in my user record I have user.locale = "en" or "sp" (or should I enumerate locales 0,1,2?)
how would I do a user specific
msg_out = t :thank_you
that would apply to every message created for that user in the current session?
If all your messages are generated when the user is using your site (i.e. all messages are sent as responses to user actions), you can just read the preferred locale out of the User model in a before_filter on your Application Controller (more on this here):
class ApplicationController < ActionController::Base
before_filter :load_user
before_filter :load_locale
#...
def load_locale
I18n.locale = (@user && @user.locale)? @user.locale : I18n.default_locale
end
#...
end
If you're sending your messages asynchronously (e.g. nightly mass-mailings), you'll have to load it per user:
User.find_each do |user|
I18n.locale = user.locale || I18n.default_locale
# Send your message...
end
And if you're sending generic mass-emails (i.e. with no per-user customizations), you can probably speed the above code up drastically by loading lists of users grouped by locale, and then sending a single message to all of them at once.
Hope this helps!
精彩评论