Class: BusinessTime::BusinessHours

Inherits:
Object
  • Object
show all
Defined in:
lib/business_time/business_hours.rb

Instance Method Summary collapse

Constructor Details

#initialize(hours) ⇒ BusinessHours

Returns a new instance of BusinessHours.


4
5
6
# File 'lib/business_time/business_hours.rb', line 4

def initialize(hours)
  @hours = hours
end

Instance Method Details

#after(time) ⇒ Object Also known as: since


16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
# File 'lib/business_time/business_hours.rb', line 16

def after(time)
  after_time = Time.roll_forward(time)
  # Step through the hours, skipping over non-business hours
  @hours.times do
    after_time = after_time + 1.hour

    if after_time.hour == 0 && after_time.min == 0 && after_time.sec == 0
      after_time = Time.roll_forward(after_time)
    elsif (after_time > Time.end_of_workday(after_time))
      # Ignore hours before opening and after closing
      delta = after_time - Time.end_of_workday(after_time)
      after_time = Time.roll_forward(after_time) + delta
    end

    # Ignore weekends and holidays
    while !Time.workday?(after_time)
      after_time = after_time + 1.day
    end
  end
  after_time
end

#agoObject


8
9
10
# File 'lib/business_time/business_hours.rb', line 8

def ago
  Time.zone ? before(Time.zone.now) : before(Time.now)
end

#before(time) ⇒ Object


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
# File 'lib/business_time/business_hours.rb', line 39

def before(time)
  before_time = Time.roll_backward(time)
  # Step through the hours, skipping over non-business hours
  @hours.times do
    before_time = before_time - 1.hour

    if before_time.hour == 0 && before_time.min == 0 && before_time.sec == 0
      before_time = Time.roll_backward(before_time - 1.second)
    elsif (before_time <= Time.beginning_of_workday(before_time))
      # Ignore hours before opening and after closing
      delta = Time.beginning_of_workday(before_time) - before_time

      # Due to the 23:59:59 end-of-workday exception
      time_roll_backward = Time.roll_backward(before_time)
      time_roll_backward += 1.second if time_roll_backward.to_s =~ /23:59:59/

      before_time = time_roll_backward - delta
    end

    # Ignore weekends and holidays
    while !Time.workday?(before_time)
      before_time = before_time - 1.day
    end
  end
  before_time
end

#from_nowObject


12
13
14
# File 'lib/business_time/business_hours.rb', line 12

def from_now
  Time.zone ?  after(Time.zone.now) : after(Time.now)
end