Class: Periodical::Period
- Inherits:
-
Object
- Object
- Periodical::Period
- Defined in:
- lib/periodical/period.rb
Constant Summary collapse
- VALID_UNITS =
[:days, :weeks, :months, :years]
Instance Attribute Summary collapse
-
#count ⇒ Object
readonly
Returns the value of attribute count.
-
#unit ⇒ Object
readonly
Returns the value of attribute unit.
Class Method Summary collapse
-
.parse(value) ⇒ Object
Accepts strings in the format of “2 weeks” or “weeks”.
Instance Method Summary collapse
- #advance(date, multiple = 1) ⇒ Object
-
#initialize(count = 1, unit = :days) ⇒ Period
constructor
A new instance of Period.
- #to_formatted_s ⇒ Object
- #to_s ⇒ Object
Constructor Details
#initialize(count = 1, unit = :days) ⇒ Period
Returns a new instance of Period.
67 68 69 70 |
# File 'lib/periodical/period.rb', line 67 def initialize(count = 1, unit = :days) @count = count @unit = unit end |
Instance Attribute Details
#count ⇒ Object (readonly)
Returns the value of attribute count.
99 100 101 |
# File 'lib/periodical/period.rb', line 99 def count @count end |
#unit ⇒ Object (readonly)
Returns the value of attribute unit.
98 99 100 |
# File 'lib/periodical/period.rb', line 98 def unit @unit end |
Class Method Details
.parse(value) ⇒ Object
Accepts strings in the format of “2 weeks” or “weeks”
26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 |
# File 'lib/periodical/period.rb', line 26 def self.parse(value) if Array === value parts = value else parts = value.to_s.split(/\s+/, 2) end if parts.size == 1 if parts[0].to_i == 0 count = 1 unit = parts[0].to_sym else count = parts[0].to_i unit = :days if count == 7 count = 1 unit = :weeks end if count == 365 count = 1 unit = :years end end else count = parts[0].to_i unit = parts[1].gsub(/\s+/, '_').downcase.to_sym end unless VALID_UNITS.include? unit raise ArgumentError.new("Invalid unit specified #{unit}!") end if count == 0 raise ArgumentError.new("Count must be non-zero!") end return self.new(count, unit) end |
Instance Method Details
#advance(date, multiple = 1) ⇒ Object
84 85 86 87 88 89 90 91 92 93 94 95 96 |
# File 'lib/periodical/period.rb', line 84 def advance(date, multiple = 1) total = multiple * @count if unit == :days date + total elsif unit == :weeks date + (total * 7) elsif unit == :months date >> total elsif unit == :years date >> (total * 12) end end |
#to_formatted_s ⇒ Object
76 77 78 79 80 81 82 |
# File 'lib/periodical/period.rb', line 76 def to_formatted_s if @count == 1 @unit.to_s.gsub(/s$/, '') else to_s end end |
#to_s ⇒ Object
72 73 74 |
# File 'lib/periodical/period.rb', line 72 def to_s "#{@count} #{@unit}" end |