From d6b65dbc0168540581de534e3fd35857288b4f19 Mon Sep 17 00:00:00 2001 From: Jim Myhrberg Date: Thu, 29 Jul 2010 03:34:31 +0300 Subject: [PATCH] restructured files a bit --- .../{time.rb => core_ext/calculations.rb} | 0 lib/time_ext/core_ext/ranges.rb | 56 +++++++++++++++++++ 2 files changed, 56 insertions(+) rename lib/time_ext/{time.rb => core_ext/calculations.rb} (100%) create mode 100644 lib/time_ext/core_ext/ranges.rb diff --git a/lib/time_ext/time.rb b/lib/time_ext/core_ext/calculations.rb similarity index 100% rename from lib/time_ext/time.rb rename to lib/time_ext/core_ext/calculations.rb diff --git a/lib/time_ext/core_ext/ranges.rb b/lib/time_ext/core_ext/ranges.rb new file mode 100644 index 0000000..69a636a --- /dev/null +++ b/lib/time_ext/core_ext/ranges.rb @@ -0,0 +1,56 @@ +class Time + + # Executes passed block for each unit of time specified + def each(unit, &block) + if block_given? + @each_until ||= self.tomorrow #TODO should be next larger unit + time = self.clone + while time <= @each_until + yield(time) + time = time.send("next_#{unit}") + end + self + else + @method_chain ||= [] + @method_chain << [:each, [unit]] + self + end + end + alias :iterate :each + alias :beginning_of_each :each + + # Executes passed block for each unit of time specified + def map(unit, &block) + if block_given? + @each_until ||= self.tomorrow #TODO should be next larger unit + time = self.clone + result = [] + while time <= @each_until + result << yield(time) + time = time.send("next_#{unit}") + end + result + else + @method_chain ||= [] + @method_chain << [:map, [unit]] + self + end + end + alias :iterate :each + + # Used togeter with #each to specify end of interation + def until(time, &block) + time = time.to_time if time.is_a?(::Date) + @each_until = time + if block_given? + method, args = @method_chain.pop + self.send(method, *args, &block) + else + @method_chain ||= [] + @method_chain << [:until, [time]] + self + end + end + alias :till :until + +end \ No newline at end of file