Last active
June 2, 2022 05:41
-
-
Save dvodvo/c8aad4e49a303c636aea384cbdae9007 to your computer and use it in GitHub Desktop.
quick and dirty I18n with Mobility
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This is intended as a 'minimal amount of steps' to get Mobility running properly | |
• rails generate mobility:install | |
• edit `config/initializers/mobility.rb` | |
- uncomment `dirty`</li> | |
- uncomment `locale_accessors` and set desired locales | |
• rails db:migrate | |
• setup model | |
extend Mobility | |
translates :synopsis, type: :string | |
translates :full_text, type: :text # attributes for translation | |
• adjust controller params | |
translated_params = (I18n.available_locales.map do |l| | |
[:"question_#{Mobility.normalize_locale(l)}", :"correct_answer_#{Mobility.normalize_locale(l)}"] | |
end.flatten) | |
params.require(:model).permit(:[... attributes], translated_params) | |
• create a `before_action :set_locale` method | |
def set_locale | |
if user_signed_in? | |
I18n.locale = current_user.idiom.label.downcase | |
else | |
if !params[:locale].nil? | |
session[:locale] = params[:locale] | |
end | |
I18n.locale = session[:locale] || I18n.default_locale | |
end | |
end | |
or variant thereof</li> | |
• adjust navigation if toggling to be publicly accessible | |
<% I18n.available_locales.each do |locale| %> | |
<% next if locale == I18n.locale %> | |
<%= link_to locale.to_s, url_for( request.params.merge(locale: locale)), class: 'locale small', style: 'margin-top: -5px;' %> | |
<% end %> | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment