Christophe Cuypers
Christophe Cuypers

Reputation: 31

How to use my little class from ruby on ruby on rails

I have wrote one little class on ruby, and i want to use she, on ruby on rails, for showing on each pages, date and hours on french, how to be good placed, she on for having on each views ? if possible to explain, whole procees ? Many thanks, Here is she..

# Petite classe pour récupérer le jour et l'heure en Français
class JourFrancais

    def initialize()
        self.jourj
    end
    def jourj
        jours_ouvrables = {Lundi: 'monday', Mardi: 'tuesday', Mercredi: 'wednesday', Jeudi: 'thursday', Vendredi: 'friday', Samedi: 'saturday', Dimanche: 'sunday'}


        jours_ouvrables.each do |key, value|
            if Time.now.strftime("%A").downcase == value
            puts "Nous sommes le #{key} " + Time.now.strftime("%d/%m/%Y") + " et il est " + Time.now.strftime("%H:%M")

            end
        end
    end 
end

thanks for your help..

Upvotes: 2

Views: 48

Answers (2)

Eric Duminil
Eric Duminil

Reputation: 54223

Your library

Here's a small refactoring of your class:

# Petite classe pour récupérer le jour et l'heure en Français
class JourFrancais
  JOURS = {"Monday"=>"Lundi", "Tuesday"=>"Mardi", "Wednesday"=>"Mercredi", "Thursday"=>"Jeudi", "Friday"=>"Vendredi", "Saturday"=>"Samedi", "Sunday"=>"Dimanche"}

  def self.jourj(time = Time.now)
    jour = JOURS[time.strftime('%A')]
    "Nous sommes le #{jour} " + time.strftime("%d/%m/%Y et il est %H:%M.")
  end
end 

puts JourFrancais.jourj
# "Nous sommes le Dimanche 17/03/2019 et il est 21:14."
puts JourFrancais.jourj(Time.local(2017, 3, 1, 12, 35))
# "Nous sommes le Mercredi 01/03/2017 et il est 12:35."

No need for a loop, the method now returns a string instead of just displaying it and you can specify the time.

With Rails i18n

In Rails, you could download fr.yml to config/locales/ and add config.i18n.default_locale = :fr to your config/application.rb.

You don't need your library anymore!

I18n.l Time.now, format: :long
# => "dimanche 17 mars 2019 21h23"

Upvotes: 2

Antarr Byrd
Antarr Byrd

Reputation: 26061

You can add the class to the lib directory of your app.

Then in application.rb include that directory

config.autoload_paths << "#{Rails.root}/lib"

Upvotes: 1

Related Questions