Class: Timely::DateGroup

Inherits:
ActiveRecord::Base
  • Object
show all
Defined in:
lib/timely/rails/date_group.rb

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.from_patterns(patterns) ⇒ Object



43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
# File 'lib/timely/rails/date_group.rb', line 43

def self.from_patterns(patterns)
  date_groups = []
  Array.wrap(patterns).each do |pattern|
    if pattern.frequency.unit == :weeks
      weekdays = pattern.intervals.map { |i| i.first_datetime.wday }.inject({}) do |hash, wday|
        hash[wday] = 1
        hash
      end
      date_groups << DateGroup.new(
        :start_date => pattern.first_datetime.to_date,
        :end_date => pattern.last_datetime.to_date,
        :weekdays => weekdays)
    elsif pattern.frequency.unit == :days && pattern.frequency.duration == 1.day
      date_groups << DateGroup.new(
        :start_date => pattern.first_datetime.to_date,
        :end_date => pattern.last_datetime.to_date,
        :weekdays => 127)
    else
      pattern.datetimes.each do |datetimes|
        datetimes.group_by(&:week).values.each do |dates|
          weekdays = dates.map(&:wday).inject({}) do |hash, wday|
            hash[wday] = 1
            hash
          end
          date_groups << DateGroup.new(
            :start_date => dates.min.to_date.beginning_of_week,
            :end_date => dates.max.to_date.end_of_week,
            :weekdays => weekdays)
        end
      end
    end
  end
  date_groups
end

Instance Method Details

#applicable_for_duration?(date_range) ⇒ Boolean

Returns:

  • (Boolean)


14
15
16
17
18
19
20
21
22
# File 'lib/timely/rails/date_group.rb', line 14

def applicable_for_duration?(date_range)
  if date_range.first > end_date || date_range.last < start_date
    false
  elsif weekdays.all_days?
    true
  else
    date_range.intersecting_dates(start_date..end_date).any?{|d| weekdays.applies_for_date?(d)}
  end
end

#datesObject



24
25
26
# File 'lib/timely/rails/date_group.rb', line 24

def dates
  start_date.upto(end_date).select { |d| weekdays.applies_for_date?(d) }
end

#includes_date?(date) ⇒ Boolean

Returns:

  • (Boolean)


10
11
12
# File 'lib/timely/rails/date_group.rb', line 10

def includes_date?(date)
  date >= start_date && date <= end_date && weekdays.applies_for_date?(date)
end

#patternObject

—————- Date intervals and patterns —————–#



38
39
40
41
# File 'lib/timely/rails/date_group.rb', line 38

def pattern
  ranges = dates.group_by(&:wday).values.map { |weekdates| (weekdates.min..weekdates.max) }
  TemporalPatterns::Pattern.new(ranges, 1.week)
end

#to_sObject



28
29
30
31
32
# File 'lib/timely/rails/date_group.rb', line 28

def to_s
  str = start_date && end_date ? (start_date..end_date).to_date_range.to_s : (start_date || end_date).to_s
  str += " on #{weekdays}" unless weekdays.all_days?
  str
end