Class: Periodical::Period

Inherits:
Struct
  • Object
show all
Defined in:
lib/periodical/period.rb

Constant Summary collapse

VALID_UNITS =
[:days, :weeks, :months, :years].freeze

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(count = 1, unit = :days) ⇒ Period

Plural is preferred, as in “1 or more days”.



26
27
28
# File 'lib/periodical/period.rb', line 26

def initialize(count = 1, unit = :days)
  super(count, unit)
end

Instance Attribute Details

#countObject

Returns the value of attribute count

Returns:

  • (Object)

    the current value of count



22
23
24
# File 'lib/periodical/period.rb', line 22

def count
  @count
end

#unitObject

Returns the value of attribute unit

Returns:

  • (Object)

    the current value of unit



22
23
24
# File 'lib/periodical/period.rb', line 22

def unit
  @unit
end

Class Method Details

.dump(period) ⇒ Object



85
86
87
# File 'lib/periodical/period.rb', line 85

def dump(period)
  period.to_s if period
end

.load(string) ⇒ Object



77
78
79
80
81
82
83
# File 'lib/periodical/period.rb', line 77

def load(string)
  if string
    string = string.strip
    
    parse(string) unless string.empty?
  end
end

.parse(string) ⇒ Object

Accepts strings in the format of “2 weeks” or “weeks”



64
65
66
67
68
69
70
71
72
73
74
75
# File 'lib/periodical/period.rb', line 64

def parse(string)
  parts = string.split(/\s+/, 2)
  
  if parts.size == 1
    count = 1
    unit = parts[0]
  else
    count, unit = parts
  end
  
  self.new(count.to_i, unit.to_sym)
end

Instance Method Details

#advance(date, multiple = 1) ⇒ Object

Raises:

  • (TypeError)


38
39
40
41
42
# File 'lib/periodical/period.rb', line 38

def advance(date, multiple = 1)
  raise TypeError unless date.is_a?(Date)
  
  self.send("advance_#{unit}", date, multiple * self.count)
end

#to_sObject



30
31
32
33
34
35
36
# File 'lib/periodical/period.rb', line 30

def to_s
  if self.count != 1
    "#{self.count} #{self.unit}"
  else
    self.unit.to_s
  end
end