Skip to content

Instantly share code, notes, and snippets.

@morimori
Created April 2, 2009 06:57
Show Gist options
  • Save morimori/89063 to your computer and use it in GitHub Desktop.
Save morimori/89063 to your computer and use it in GitHub Desktop.
Date と Time に直前と直後の各曜日を取得するメソッドを追加
class Date
module Extender
module LastAndNext
['sunday', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday'].each_with_index do |weekday, index|
define_method "last_#{weekday}" do
return self if wday == index
offset = wday - index
self - (offset < 0 ? offset + 7 : offset)
end
define_method "next_#{weekday}" do
return self if wday == index
offset = wday - index
self + (7 - (offset < 0 ? offset + 7 : offset))
end
end
end
end
include Extender::LastAndNext
end
class Time
module Extender
module LastAndNext
['sunday', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday'].each_with_index do |weekday, index|
define_method "last_#{weekday}" do
return self if wday == index
offset = wday - index
self - (offset < 0 ? offset + 7 : offset) * 86400
end
define_method "next_#{weekday}" do
return self if wday == index
offset = wday - index
self + (7 - (offset < 0 ? offset + 7 : offset)) * 86400
end
end
end
end
include Extender::LastAndNext
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment