How to render images from Markdown files with Rails 5.2? - ruby-on-rails

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?

Related

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

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).

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

Ruby on Rails flash messages in French

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.

Cucumber steps definitions in spanish: Ambiguous match of "..."

I'm trying to translate the steps definitions of cucumber to spanish but I'm getting this error:
Ambiguous match of "que estoy en la página "inicio de sesión""
features/step_definitions/web_steps.rb:3:in `/^que estoy en la página "([^"]*)"$/'
features/step_definitions/web_steps.rb:7:in `/^visito la pa|ágina "([^"]*)"$/'
Here's my web_steps.rb
# encoding: utf-8
Dado /^que estoy en la página "([^"]*)"$/ do |page|
visit(path_to page)
end
Cuando /^visito la página "([^"]*)"$/ do |page|
visit(path_to page)
end
How can that be ambiguos if I got the ^ and the $ in the regexp?
It looks like it's seeing a | in the latter step definition. Look closely at the second line of the error:
features/step_definitions/web_steps.rb:3:in `/^que estoy en la página "([^"]*)"$/'
features/step_definitions/web_steps.rb:7:in `/^visito la pa|ágina "([^"]*)"$/'
It's seeing /^visito la pa|ágina "([^"]*)"$/, which it interprets as an OR, i.e. /^visito la pa OR ágina "([^"]*)"$/. With that interpretation, the match does indeed become ambiguous.
Now why it is reading it that way is a mystery to me, perhaps some UTF-8 garbling?

Resources