Class: TimeCrisis::DateRange

Inherits:
Range
  • Object
show all
Defined in:
lib/time_crisis/date_range.rb

Defined Under Namespace

Modules: Date

Instance Method Summary collapse

Constructor Details

#initialize(*args) ⇒ DateRange



2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
# File 'lib/time_crisis/date_range.rb', line 2

def initialize(*args)
  options = args.last.is_a?(Hash) ? args.pop : {}

  # make compatibile with Range's normal arguments
  options[:begin] = args.shift unless args.empty?
  options[:end] = args.shift unless args.empty?
  options[:exclude_end] = args.shift unless args.empty?

  start = options[:begin].nil? ? false : options[:begin].to_date
  stop = options[:end].nil? ? false : options[:end].to_date

  unit = options[:unit] || 1
  scale = options[:scale] || 'years'
  scale = scale.pluralize if scale.respond_to?(:pluralize)

  if start && !stop
    stop = start.advance({scale.to_sym => unit, :days => -1})
  elsif !start && stop
    start = stop.advance({scale.to_sym => -unit, :days => 1})
  end

  super(start, stop, options[:exclude_end] || false)
end

Instance Method Details

#each_month(&block) ⇒ Object



63
64
65
# File 'lib/time_crisis/date_range.rb', line 63

def each_month(&block)
  each_slice_by_period(:months, 1, &block)
end

#each_slice_by_date(*args) {|self.class.new(start, self.end, self.exclude_end?)| ... } ⇒ Object

Yields:

  • (self.class.new(start, self.end, self.exclude_end?))


30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
# File 'lib/time_crisis/date_range.rb', line 30

def each_slice_by_date(*args, &block)
  dates = args.map! do |datelike|
    date = datelike.to_date
    raise ArgumentError, "Date not within range: #{date}" unless self.include?(date)
    date
  end
  dates.sort!

  start = self.begin

  dates.each do |date|
    yield self.class.new(start, date, true)
    start = date
  end

  yield self.class.new(start, self.end, self.exclude_end?)
end

#each_slice_by_period(period, unit = 1) {|self.class.new(start, self.end, self.exclude_end?)| ... } ⇒ Object

Yields:

  • (self.class.new(start, self.end, self.exclude_end?))

Raises:

  • (ArgumentError)


48
49
50
51
52
53
54
55
56
57
58
59
60
61
# File 'lib/time_crisis/date_range.rb', line 48

def each_slice_by_period(period, unit=1, &block)
  start = self.begin
  nstart = start.advance(period.to_sym => unit)

  raise ArgumentError, "Period exceeds range" if nstart >= self.real_end

  while nstart < self.real_end
    yield self.class.new(start, nstart, true)
    start = nstart
    nstart = start.advance(period.to_sym => unit)
  end

  yield self.class.new(start, self.end, self.exclude_end?)
end

#each_year(&block) ⇒ Object



67
68
69
# File 'lib/time_crisis/date_range.rb', line 67

def each_year(&block)
  each_slice_by_period(:years, 1, &block)
end

#include?(datelike) ⇒ Boolean



26
27
28
# File 'lib/time_crisis/date_range.rb', line 26

def include?(datelike)
  super(datelike.to_date)
end