Modifier la classe Date

Salut,

Je suis en train de bosser sur une petite appli qui affiche un
calendrier, et à cette occasion j’ai eu besoin d’ajouter quelques
fonctions à la classe Date.
J’ai donc ajouté un fichier date.rb dans config/initializers (voir
ci-dessous).
Deux questions :

  1. Est-ce bien comme ça que je dois procéder ?
  2. Je ne suis pas très satisfait du code de ma fonction
    weeks_of_month … quelqu’un à mieux à me proposer ?

Merci
Emmanuel


require ‘date’

class Date
def is_weekend?
self.wday == 6 || self.wday == 0
end

def is_weekday?
!self.is_weekend?
end

def week_number
self.strftime("%W").to_i % 52 + 1
end

def week
Array.new(7) { |offset| self.at_beginning_of_week + offset.days }
end

def weeks_of_month
weeks = Array.new
next_month = (self + 1.month).month
current_day = self.at_beginning_of_month.at_beginning_of_week
while current_day.month != next_month
weeks << current_day.week
current_day += 7.days
end
weeks
end
end

Le 7 novembre 2008 23:45, Emmanuel B. a écrit :

Je suis en train de bosser sur une petite appli qui affiche un
calendrier, et à cette occasion j’ai eu besoin d’ajouter quelques
fonctions à la classe Date.
J’ai donc ajouté un fichier date.rb dans config/initializers
(voir ci-dessous).
Deux questions :

  1. Est-ce bien comme ça que je dois procéder ?

ça peut se mettre dans lib/ mais ça peut se mettre dans
config/initializers oui.

  1. Je ne suis pas très satisfait du code de ma fonction
    weeks_of_month … quelqu’un à mieux à me proposer ?

def weeks_of_month
weeks = Array.new
next_month = (self + 1.month).month
current_day = self.at_beginning_of_month.at_beginning_of_week
while current_day.month != next_month
weeks << current_day.week
current_day += 7.days
end
weeks
end

à vérifier que c’est blindé…

def weeks_of_month
from = at_beginning_of_month.at_beginning_of_week
to = at_end_of_month.at_end_of_week
weeks = (from…to).to_a.in_groups_of 7
end

– Jean-François.


http://twitter.com/underflow_

Jean-François,

Ta version de weeks_of_month me plait bien … et elle semble
fonctionner impeccable :slight_smile:
Merci beaucoup !

Emmanuel

Le 8 novembre 2008 00:37, Jean-François Trân [email protected] a écrit :