Ruby on Rails flash messages in French - ruby-on-rails

Working on a rails app in French, however whenever i include an accent on the flash messages it breaks the site.
For example
format.html {redirect_to #message.annonce, notice:"Votre message a été envoyé"}
format.html {redirect_to #message.annonce, notice:"Votre email n'a pas pu être envoyer à cause d'une erreur."}
my config/application.rb looks like this
config.i18n.default_locale = :fr
config.encoding = "utf-8"
How does one do about this?

You should add # encoding: UTF-8 as the first line of your file to add accent in it.
If this is not working please give us the exception raised.

Related

How to render images from Markdown files with Rails 5.2?

I based my applications inline help on Markdown files, implemented with Redcarpet gem. Contextual help is displayed as expected, but embedded images are not.
The help files structure in the project is:
public/help/administration/Connection
- Business_resources_hierarchy.png
- connections-fr.md
The connection-fr.md files contains:
# CONNECTIONS
Décrit la gestion des connexions aux ressources de l'infrastructure informatique.
## Principe de fonctionnement
La connaissance des ressources techniques comporte un certain niveau de complexité :
* adresses IP et protocoles des services
* login et mot de passe des utilisateurs techniques
* droits d'utilisation de la ressource
* multipliés par le nombre d'environnements déployés dans l'organisation (Dev, Test, Prod ...)
La gestion des connexions permet au métier de s'affranchir de cette complexité en offrant une vue métier des ressources nécessaires à la production statistique au travers d'une hiérarchie :
![Hiérarchie des resources métiers](Business_resources_hierarchy.png)
## Eléments d'infrastructure
1. Les ressources métiers - offrent une vue fonctionnelle des
Markdown is supported by the application_helper.rb:
module ApplicationHelper
### Implementing Help files management with Markdown
def markdown
markdown = Redcarpet::Markdown.new(Redcarpet::Render::HTML, :autolink => true, :space_after_headers => true, tables: true)
end
def displayHelp
puts "Help requested for: #{params[:page_name]}.#{params[:format]}"
# Parse the request from the page -> namespace/class/controller
if params[:page_name].index('/')
domain = params[:page_name].split('/')[0]
page = params[:page_name].split('/')[1]
else
domain = ''
page = params[:page_name]
end
method = params[:format] # The method from the controller is not used yet
# Build the help file path and name using the current locale
case page
when 'Change_Log' # Does it still exist?
filename = File.join(Rails.root, 'public', "CHANGELOG.md")
when 'Release_notes' # Does it still exist?
filename = File.join(Rails.root, 'public', "Release_notes.md")
else
filename = File.join(Rails.root,
'public',
'help',
domain,
page.classify,
"#{page}-#{I18n.locale.to_s[0,2]}.md"
)
end
puts "Requested help file: #{filename}"
if not File.file?(filename)
filename = File.join(Rails.root, 'public', 'help', "help-index-#{I18n.locale.to_s[0,2]}.md")
end
begin
file = File.open(filename, "rb")
markdown.render(file.read).html_safe.force_encoding('UTF-8')
rescue Errno::ENOENT
render :file => "public/404.html", :status => 404
end
end
end
I tried a few ways to define the path to the image file, but it does not show up. When submitting the file URL to Rails, it raises the following error:
No route matches [GET] "/Business_resources_hierarchy.PNG"
How to define the path to the file, or configure the helper so that the image is displayed?

How to fix: i18n always translate to default locale

I'm trying out the internationalization of a Rails app with i18n. I did some small tests with 2 languages: english and french.
The problem I have is that i18n always translate to the default locale. So if it's english, everything will be in english, and the same with french.
Here is what I tried:
config/initializers/locales.rb
# Permitted locales available for the application
I18n.available_locales = [:en, :fr]
app/controllers/application_controller.rb
class ApplicationController < ActionController::Base
def default_url_options
{ locale: I18n.locale }
end
end
config/application.rb
module LanguageApp
class Application < Rails::Application
...
config.i18n.load_path += Dir["#{Rails.root.to_s}/config/locales/**/*.{rb,yml}"]
config.i18n.default_locale = :en
# I change the default locale here to :fr or :en
end
end
config/routes.rb
root to: "home#index"
get '/:locale/about' => 'about#index'
get '/:locale' => 'home#index'
I organized my yml files like this:
config/locales/views/about/en.yml
en:
about: "This page is about us."
config/locales/views/about/fr.yml
fr:
about: "Cette page est à propos de nous."
config/locales/views/home/en.yml
en:
welcome: "Hello world"
config/locales/views/home/fr.yml
fr:
welcome: "Bonjour le monde"
And finally my views:
app/views/about/index.html.erb
About us page. <%= t(:about) %>
app/views/home/index.html.erb
This is the homepage. <%= t(:welcome) %>
I think the problem may come from the way I organized my yml files but I don't understand why i18n only translate to the default locale and 'ignore' the other language.
EDIT:
To try this out in the browser with the rails server running, I tried to visit these URL:
localhost:3000
localhost:3000/en
localhost:3000/fr
These 3 URL give me the same content, so the :fr locale doesn't actually work (it returns the same translation as :en)
Same for
localhost:3000/en/about
localhost:3000/fr/about
I also tried it in the rails console:
> I18n.t(:welcome, :en)
"Hello world"
> I18n.t(:welcome, :fr)
"Hello world"
First set the locale for the request:
class ApplicationController < ActionController::Base
around_action :switch_locale
def switch_locale(&action)
I18n.with_locale(params[:locale] || I18n.default_locale, &action)
end
def default_url_options
{ locale: I18n.locale }
end
end
Don't use I18n.locale= as many older answers / tutorials do.
I18n.locale can leak into subsequent requests served by the same
thread/process if it is not consistently set in every controller. For
example executing I18n.locale = :es in one POST requests will have
effects for all later requests to controllers that don't set the
locale, but only in that particular thread/process. For that reason,
instead of I18n.locale = you can use I18n.with_locale which does not
have this leak issue.
Rails Guides
If you want to create translations for specific views you should nest the keys instead of just using flat hashes:
en:
home:
welcome: "Hello World"
fr:
home:
welcome: "Bonjour le monde"
And then use an implicit lookup in the view:
<h1><%= t('.welcome') %></h1>
This resolves the key to home.welcome.

How to use English text when corresponding language text doesn't exist

I have text like this
config/locales/en.yml
record_your_voice: 'Record your voice?'
When I'm seeing the page in Japanese local config, the text Record Your Voice is shown - the capitalized left side of code.
How can I use the text "Record your voice?" when corresponding Japanese text failed.
The answer is given here
in your application.rb file, you have the following options :
# rails will fallback to config.i18n.default_locale translation
config.i18n.fallbacks = true
# rails will fallback to en, no matter what is set as config.i18n.default_locale
config.i18n.fallbacks = [:en]
# fallbacks value can also be a hash - a map of fallbacks if you will
# missing translations of es and fr languages will fallback to english
# missing translations in german will fallback to french ('de' => 'fr')
config.i18n.fallbacks = {'es' => 'en', 'fr' => 'en', 'de' => 'fr'}

Load languages files with I18n

I have a problem to load files with I18n.
Befor I had all my translations in only one file called fr.yml.
But I decied to split them in some files like clubs.fr.yml, searcher.fr.yml ...
The problem it that I18n apparently only load fr.yml.
Here my code to load files :
I18n.load_path += Dir[Rails.root.join('my', 'locales', '*.{rb,yml}').to_s]
I18n.default_locale = :fr
and here an exemple of one of my files :
fr:
searcher:
search: "Rechercher..."
title: "Recherche sur :"
clubs:
title: "Liste des Clubs"
name: "Nom du club"
description: "Description"
show: "Voir"
no_result: "Aucun clubs n'a été trouvé pour cette recherche."
I checked and it's space and no tab. Any idea ?
Comment first line. By default all yml files will be loaded.
Also restart the server.
# config/application.rb
. . .
config.i18n.default_locale = :fr
. . .
# in view
<%= t 'searcher.search' %>
The problem was that I didn't restart my server ... Shame on me !!!

Translation of devise not working

I am using devise for the user registration... and i want to translate it in French, I get the file traduction :
fr:
errors:
messages:
not_found: "n'a pas été trouvé(e)"
already_confirmed: "a déjà été confirmé(e)"
not_locked: "n'était pas verrouillé(e)"
not_saved:
one: "1 erreur a empéché ce %{resource} d'être sauvegardé:"
other: "%{count} erreurs ont empéché ce %{resource} d'être sauvegardé:"
devise:
shared:
sign_in: "Se connecter"
sign_up: "S'enregistrer"
forgot_password: "Mot de passe oublié ?"
didnt_receive_confirmation_instructions?: "Vous n'avez pas reçu de courriel de confirmation ?"
didnt_receive_unlock_instructions?: "Vous n'avez pas reçu de courriel de déverrouillage de votre compte ?"
sign_in_with_omniauth: "Se connecter avec %{provider}"
.....
.....
And i write this on my config/application.rb :
config.i18n.default_locale = :fr
I have reboot apache but nothing to do, i don't have any traduction on messages as "Sign In Successfull..."
Any idea?
Thank you
My solution was to add
I18n.locale = :fr
If you have a problem with the production environnement, you can use :
config.before_configuration do
I18n.load_path += Dir[Rails.root.join('config', 'locales', '*.{rb,yml}').to_s]
I18n.locale = :fr
I18n.default_locale = :fr
config.i18n.load_path += Dir[Rails.root.join('config', 'locales', '*.{rb,yml}').to_s]
config.i18n.locale = :fr
# bypasses rails bug with i18n in production\
I18n.reload!
config.i18n.reload!
end
config.i18n.locale = :fr
config.i18n.default_locale = :fr
In config/application.rb
This is what I just did and it works:
copy devise.fr.yml to config/locales
add "config.i18n.default_locale = :fr" to config/application.rb
reboot mongrel

Resources