Class: Daru::DateOffset

Inherits:
Object show all
Defined in:
lib/daru/date_time/offsets.rb

Overview

Generic class for generating date offsets.

Direct Known Subclasses

Offsets::DateOffsetType, Offsets::Week

Instance Method Summary collapse

Constructor Details

#initialize(opts = {}) ⇒ DateOffset

A Daru::DateOffset object is created by a passing certain options to the constructor, which determine the kind of offset the object will support.

You can pass one of the following options followed by their number to the DateOffset constructor:

  • :secs - Create a seconds offset

  • :mins - Create a minutes offset

  • :hours - Create an hours offset

  • :days - Create a days offset

  • :weeks - Create a weeks offset

  • :months - Create a months offset

  • :years - Create a years offset

Additionaly, passing the ‘:n` option will apply the offset that many times.

Examples:

Usage of DateOffset

# Create an offset of 3 weeks.
offset = Daru::DateOffset.new(weeks: 3)
offset + DateTime.new(2012,5,3)
#=> #<DateTime: 2012-05-24T00:00:00+00:00 ((2456072j,0s,0n),+0s,2299161j)>

# Create an offset of 5 hours
offset = Daru::DateOffset.new(hours: 5)
offset + DateTime.new(2015,3,3,23,5,1)
#=> #<DateTime: 2015-03-04T04:05:01+00:00 ((2457086j,14701s,0n),+0s,2299161j)>

# Create an offset of 2 minutes, applied 5 times
offset = Daru::DateOffset.new(mins: 2, n: 5)
offset + DateTime.new(2011,5,3,3,5)
#=> #<DateTime: 2011-05-03T03:15:00+00:00 ((2455685j,11700s,0n),+0s,2299161j)>


38
39
40
41
42
43
44
45
46
47
48
# File 'lib/daru/date_time/offsets.rb', line 38

def initialize opts={}
  n = opts[:n] || 1
  Offsets::LIST.each do |key, klass|
    if opts.key?(key)
      @offset = klass.new(n * opts[key])
      break
    end
  end

  @offset = Offsets::Day.new(7*n*opts[:weeks]) if opts[:weeks]
end

Instance Method Details

#+(date_time) ⇒ Object

Offset a DateTime forward.

Parameters:

  • date_time (DateTime)

    A DateTime object which is to offset.



53
54
55
# File 'lib/daru/date_time/offsets.rb', line 53

def + date_time
  @offset + date_time
end

#-(date_time) ⇒ Object

Offset a DateTime backward.

Parameters:

  • date_time (DateTime)

    A DateTime object which is to offset.



60
61
62
# File 'lib/daru/date_time/offsets.rb', line 60

def - date_time
  @offset - date_time
end

#-@Object



64
65
66
# File 'lib/daru/date_time/offsets.rb', line 64

def -@
  NegativeDateOffset.new(self)
end