Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Handle negative business days and hours #158

Merged
merged 3 commits into from
Jun 7, 2017
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
30 changes: 21 additions & 9 deletions lib/business_time/business_days.rb
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,26 @@ def <=>(other)
end

def after(time = Time.current)
days = @days
positive_days? ? calculate_after(time, @days) : calculate_before(time, -@days)
end

alias_method :from_now, :after
alias_method :since, :after

def before(time = Time.current)
positive_days? ? calculate_before(time, @days) : calculate_after(time, -@days)
end

alias_method :ago, :before
alias_method :until, :before

private

def positive_days?
@days > 0
end

def calculate_after(time, days)
while days > 0 || !time.workday?
days -= 1 if time.workday?
time += 1.day
Expand All @@ -30,11 +49,7 @@ def after(time = Time.current)
time
end

alias_method :from_now, :after
alias_method :since, :after

def before(time = Time.current)
days = @days
def calculate_before(time, days)
while days > 0 || !time.workday?
days -= 1 if time.workday?
time -= 1.day
Expand All @@ -48,8 +63,5 @@ def before(time = Time.current)
end
time
end

alias_method :ago, :before
alias_method :until, :before
end
end
22 changes: 18 additions & 4 deletions lib/business_time/business_hours.rb
Original file line number Diff line number Diff line change
Expand Up @@ -24,9 +24,24 @@ def from_now
end

def after(time)
positive_hours? ? calculate_after(time, @hours) : calculate_before(time, -@hours)
end
alias_method :since, :after

def before(time)
positive_hours? ? calculate_before(time, @hours) : calculate_after(time, -@hours)
end

private

def positive_hours?
@hours > 0
end

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

if after_time.hour == 0 && after_time.min == 0 && after_time.sec == 0
Expand All @@ -44,12 +59,11 @@ def after(time)
end
after_time
end
alias_method :since, :after

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

if before_time.hour == 0 && before_time.min == 0 && before_time.sec == 0
Expand Down