Class: Cyclical::MonthsFilter

Inherits:
Object
  • Object
show all
Defined in:
lib/cyclical/filters/months_filter.rb

Constant Summary collapse

MONTH_NAMES =
{
  :jan => 1, :january => 1,
  :feb => 2, :february => 2,
  :mar => 3, :march => 3,
  :apr => 4, :april => 4,
  :may => 5,
  :jun => 6, :june => 6,
  :jul => 7, :july => 7,
  :aug => 8, :august => 8,
  :sep => 9, :sept => 9, :september => 9,
  :oct => 10, :october => 10,
  :nov => 11, :november => 11,
  :dec => 12, :december => 12
}

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(*months) ⇒ MonthsFilter

Returns a new instance of MonthsFilter.

Raises:

  • (ArgumentError)


21
22
23
24
25
# File 'lib/cyclical/filters/months_filter.rb', line 21

def initialize(*months)
  raise ArgumentError, "Specify at least one month" if months.empty?

  @months = months.map { |m| m.is_a?(Integer) ? m : MONTH_NAMES[m.to_sym] }.sort
end

Instance Attribute Details

#monthsObject (readonly)

Returns the value of attribute months.



19
20
21
# File 'lib/cyclical/filters/months_filter.rb', line 19

def months
  @months
end

Instance Method Details

#match?(date) ⇒ Boolean

Returns:

  • (Boolean)


27
28
29
# File 'lib/cyclical/filters/months_filter.rb', line 27

def match?(date)
  @months.include?(date.mon)
end

#next(date) ⇒ Object



35
36
37
38
39
40
41
42
43
# File 'lib/cyclical/filters/months_filter.rb', line 35

def next(date)
  return date if match?(date)

  if month = @months.find { |m| m > date.month }
    date.beginning_of_year + (month - 1).months + date.hour.hours + date.min.minutes + date.sec.seconds
  else
    date.beginning_of_year + 1.year + (@months.first - 1).months + date.hour.hours + date.min.minutes + date.sec.seconds
  end
end

#previous(date) ⇒ Object



45
46
47
48
49
50
51
52
53
# File 'lib/cyclical/filters/months_filter.rb', line 45

def previous(date)
  return date if match?(date)

  if month = @months.reverse.find { |m| m < date.month }
    date.beginning_of_year + month.months - 1.day + date.hour.hours + date.min.minutes + date.sec.seconds
  else
    date.beginning_of_year - 1.year + @months.last.months - 1.day + date.hour.hours + date.min.minutes + date.sec.seconds
  end
end

#stepObject



31
32
33
# File 'lib/cyclical/filters/months_filter.rb', line 31

def step
  1.month
end