Plurals in rails mailer don't work with TextHelper - ruby-on-rails

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

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.

Rspec and Rails 4, update skip callback

I try to run an update test with rspec for my rails application.
I'm using rspec 3.5 and rails 4.
The behaviour is supposed to be the following :
When i create a new service with a selling price, it's create a Price instance and set the relation with the service. Then, when i update my service, if there is no selling price, it's destroy the price record (requirement of the client to save space in database).
The process i implemented seems to be working fine, when i test with the UI and i check the count of Price record, it's decrease by one like it's suppose. However, the unit test if failing.
Here is the code :
Service Controller :
def update
#service.assign_attributes(service_params)
puts "update method"
respond_to do |format|
if #service.valid?
if params['preview']
#service.build_previews
format.js { render 'services/preview' }
else
#service.save!
format.html { redirect_to client_trip_days_path(#client, #trip), notice: t('flash.services.update.notice') }
end
else
format.html { render :edit }
format.js { render :new }
end
end
end
The callback in the Service model :
def create_or_update_price
puts "in create or update price"
if selling_price.present? && price.present?
self.price.update_columns(:trip_id => trip.id, :currency => trip.client.currency, :purchase_price => purchase_price, :selling_price => selling_price)
elsif selling_price.present? && !price.present?
self.price = RegularPrice.create(:trip => trip, :currency => trip.client.currency, :purchase_price => purchase_price, :selling_price => selling_price)
elsif !selling_price.present? && price.present?
self.price.destroy
end
end
The test :
it "updates the lodging and destroy the price" do
puts "nombre de service avant création : "
puts Service.count
puts "nombre de prix avant création : "
puts Price.count
lodging = FactoryGirl.create(:lodging_service, selling_price: 200)
puts "nombre de service après création : "
puts Service.count
puts "nombre de prix après création : "
puts Price.count
expect(lodging.reload.price).to be_present
puts "nombre de prix avant update : "
puts Price.count
puts "id"
puts lodging.id
patch :update, client_id: client.id, trip_id: trip.id, id: lodging.to_param, service: valid_attributes_no_more_price
# patch :update, client_id: client.id, trip_id: trip.id, id: lodging.id, service: valid_attributes_with_price
puts "nombre de prix après update : "
puts Price.count
# expect{
# patch :update, client_id: client.id, trip_id: trip.id, id: lodging.id, service: valid_attributes_no_more_price
# }.to change(RegularPrice, :count).by(0)
expect(lodging.reload.price).to be_nil
end
let(:valid_attributes_no_more_price) {
attributes_for(:lodging_service, trip: trip, selling_price: "")
}
As you can see, there is a lot of puts since i try to find what is wrong.
The output is :
nombre de service avant création :
0
nombre de prix avant création :
0
in create or update price
nombre de service après création :
1
nombre de prix après création :
1
nombre de prix avant update :
1
id
10
nombre de prix après update :
1
Failure/Error: expect(lodging.reload.price).to be_nil
expected: nil
got: #<RegularPrice id: 2, label: nil, currency: "CHF", selling_price: 200.0, priceable_type: "Service", p...ated_at: "2017-07-13 08:08:47", quantity: 1, type: "RegularPrice", position: 1, purchase_price: nil>
As we can see, it's look like the callback is not fired after the update, and the action in the controller is not reached.
Have you any idea what is going wrong?
Thanks :)
PS: I always have trouble to include code in my questions, is there a tutorial on how to make it?
Since you did not mentioned your ruby version I'll assume it's 2.
First of all you need to learn how to properly debug your code in order to fix the issues yourself.
Here is what you have to do:
1.Add pry gem to your app, pry-byebug there is also a version for ruby 1.9.3.
2.Add a break point in your code
it "updates the lodging and destroy the price" do
(...) # Code here.
binding.pry # The debugger will open a console at this point
(...) # Maybe more code here
end
3.Verify all the variable and their values and see where the problem lies
In case you could not find the issue with binding.pry in your rspec file before the expect add it to after the first line of the method, and you can step through the debugger by typing next in the console opened by pry (it will be where your rails server is runnig).
If that still does not help, try and add a binding.pry in your classes and see what is the state in there.
Spend a few minutes/hours now to learn debugging and it will save you days/weeks in long term. (while you are learning you don't really know how a program should behave and that extra knowledge is priceless, after a while you only need a debugger for extremely complicated issues).

Devise Internationalization

I have setup Devise for my application and have created an fr.yml file in my locales folder in order to get error messages translated.
Here is my fr.yml file at the moment.
fr:
activerecord:
attributes:
client:
password: "Mot de passe"
email: "Email"
password_confirmation: "Confirmation du mot de passe"
remember_me: "Se souvenir de moi"
log_in: "Connection"
errors:
models:
client:
attributes:
password_confirmation:
confirmation: "Confirmation du mot de passe"
(It is pretty sketchy at the moment but I will develop it later on. )
Though a fun thing is happening: when I try to create a new user of the client model and let's say I forget to input the password confirmation, Devise returns the following error :
"Confirmation du mot de passe Confirmation du mot de passe"
It seems the error message is duplicated.
I have removed all French translations for 'password_confirmation' in my fr.yml file and got the following error :
"Password confirmation translation missing: fr.activerecord.errors.models.client.attributes.password_confirmation.confirmation"
Not sure what I can do to get the fr.yml right
I honestly don't know exactly why this is happening but you aren't following Devise localization standards.
Please check devise fr.yml from Devise-i18n project here : https://github.com/tigrish/devise-i18n/blob/master/rails/locales/fr.yml - you don't have to install the gem -.

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