Translation of devise not working - ruby-on-rails

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

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?

Plurals in rails mailer don't work with TextHelper

I'm trying to pluralize a word in the subject of a rails mailer :
these two don't working :
subject: "Réservation pour #{pluralize(#step.number_of_people.to_i, "personne")}"
subject: "Réservation pour #{pluralize(#step.number_of_people.to_i, "personne", locale: :fr)}"
but these two are working :
subject: "Réservation pour #{pluralize(#step.number_of_people.to_i, "personne", plural: 'personnes')}"
subject: "Réservation pour #{#step.number_of_people.to_i} #{"personne".pluralize(#step.number_of_people.to_i)}"
inflections.rb :
module Inflections
ActiveSupport::Inflector.inflections(:fr) do |inflect|
inflect.plural(/$/, 's')
inflect.singular(/s$/, '')
inflect.plural(/(bijou|caillou|chou|genou|hibou|joujou|pou|au|eu|eau)$/, '\1x')
inflect.singular(/(bijou|caillou|chou|genou|hibou|joujou|pou|au|eu|eau)x$/, '\1')
inflect.plural(/(bleu|émeu|landau|lieu|pneu|sarrau)$/, '\1s')
inflect.plural(/al$/, 'aux')
inflect.plural(/ail$/, 'ails')
inflect.singular(/(journ|chev)aux$/, '\1al')
inflect.singular(/ails$/, 'ail')
inflect.plural(/(b|cor|ém|gemm|soupir|trav|vant|vitr)ail$/, '\1aux')
inflect.singular(/(b|cor|ém|gemm|soupir|trav|vant|vitr)aux$/, '\1ail')
inflect.plural(/(s|x|z)$/, '\1')
inflect.irregular('monsieur', 'messieurs')
inflect.irregular('madame', 'mesdames')
inflect.irregular('mademoiselle', 'mesdemoiselles')
end
end

i18n dont find the translation

I18n cant find the translation even if the translation is present in my YML,
translation missing: fr.activerecord.errors.models.user.attributes.email.not_found
errors:
messages:
already_confirmed: a déjà été confirmé(e)
confirmation_period_expired: doit être confirmé(e) en %{period}, veuillez en demander un(e) autre
expired: est expiré, veuillez en demander un autre
not_found: n’a pas été trouvé(e)
not_locked: n’était pas verrouillé(e)
not_saved:
one: 'une erreur a empêché ce (cet ou cette) %{resource} d’être enregistré(e) :'
other: "%{count} erreurs ont empêché ce (cet ou cette) %{resource} d’être enregistré(e) :"
It must follows correctly the "pattern", the locale is the root, in this case fr:
fr:
activerecord:
errors:
models:
user:
attributes:
email:
not_found: Email not found

How to edit error messages in devise

I need to modify the error messages of devise. I want to change the message "is Invalid" to "Es inválido" . The problem is that I have to go to change these messages in the gem. Can I overwrite these messages in the model User
Rails console
1.9.3-p547 :014 > user.save
=> false
1.9.3-p547 :015 > user.errors
=> {:email=>["is invalid"], :password=>["is too short (minimum is 6 characters)"]}
1.9.3-p547 :016 >
User model
class User < ActiveRecord::Base
# Include default devise modules. Others available are:
# :token_authenticatable, :confirmable, :lockable and :timeoutable
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
# Setup accessible (or protected) attributes for your model
attr_accessible :email, :password, :password_confirmation, :remember_me
end
Devise Generates a devise.en.yml file in config/locales/
If you need your error messages to be in another language such as Spanish, replace your devise.en.yml with this file:
devise.es.yml
es:
errors:
messages:
expired: "ha expirado, por favor pide una nueva"
not_found: "no encontrado"
already_confirmed: "ya fue confirmada. Intenta ingresar."
not_locked: "no ha sido bloqueada"
not_saved:
one: "Ha habido 1 error:"
other: "Han habido %{count} errores:"
devise:
failure:
already_authenticated: 'Ya iniciaste sesión.'
unauthenticated: 'Tienes que registrarte o iniciar sesión antes de continuar.'
unconfirmed: 'Tienes que confirmar tu cuenta antes de continuar.'
locked: 'Tu cuente está bloqueada.'
invalid: 'Email o contraseña inválidos.'
invalid_token: 'Token de autentificación inválido.'
timeout: 'Tu sesión ha expirado. Inicia sesión nuevamente.'
inactive: 'Tu cuenta aun no ha sido activada.'
sessions:
signed_in: 'Iniciaste sesión correctamente.'
signed_out: 'Cerraste sesión correctamente.'
passwords:
send_instructions: 'Recibirás un email con instrucciones para reiniciar tu contraseña en unos minutos.'
updated: 'Tu contraseña fue cambiada correctamente. Has iniciado sesión.'
updated_not_active: 'Tu contraseña fue cambiada correctamente.'
send_paranoid_instructions: "Si tu email existe en el sistema, recibirás instrucciones para recuperar tu contraseña en él"
confirmations:
send_instructions: 'Recibirás instrucciones para confirmar tu cuenta en tu email en unos minutos.'
send_paranoid_instructions: 'Si tu email existe en el sistema, recibirás instrucciones para confirmar tu cuenta en tu email en unos minutos.'
confirmed: 'Tu cuenta fue confirmada. Has iniciado sesión.'
registrations:
signed_up: 'Bienvenido! Te has registrado correctamente.'
signed_up_but_unconfirmed: 'Te hemos enviado un email con instrucciones para que confirmes tu cuenta.'
signed_up_but_inactive: 'Te has registrado correctamente, pero tu cuenta aun no ha sido activada.'
signed_up_but_locked: 'Te has registrado correctamente, pero tu cuenta está bloqueada.'
updated: 'Actualizaste tu cuenta correctamente.'
update_needs_confirmation: "Actualizaste tu cuenta correctamente, pero tenemos que revalidar tu email. Revisa tu correo para confirmar la dirección."
destroyed: 'Adiós, tu cuenta ha sido eliminada. Esperamos verte de vuelta pronto!'
unlocks:
send_instructions: 'Recibirás un email con instrucciones para desbloquear tu cuenta en unos minutos'
unlocked: 'Tu cuenta ha sido desbloqueada. Inicia sesión para continuar.'
send_paranoid_instructions: 'Si tu cuenta existe, recibirás instrucciones para desbloquear tu cuenta en unos minutos'
omniauth_callbacks:
success: 'Te autentificaste correctamente con tu cuenta de %{kind}.'
failure: 'No pudimos autentificar tu cuenta de %{kind} por la siguiente razón: %{reason}.'
mailer:
confirmation_instructions:
subject: 'Instrucciones de confirmación'
reset_password_instructions:
subject: 'Instrucciones de cambio de contraseña'
unlock_instructions:
subject: 'Instrucciones de desbloqueo'
UPDATE
es:
activerecord:
errors:
models:
user:
attributes:
email:
blank: "El email no puede estar vacio"
This isn't Devise-specific. You can localize any of your ActiveRecord error messages in your config/locales/*.yml files.
In this case, you could, in config/local/es.yml, add something like the following:
es:
activerecord:
errors
models
user
attributes:
email:
invalid: "Es inválido"
Rails' localization is extremely configurable. There is a lot more information in the guides.
You can do the devise specific translations using the
devise.es.yml in your config/locales folder
List of all the different translations is given here in official devise wiki

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 !!!

Resources