Skip to content

Commit

Permalink
Record#calculated_durations
Browse files Browse the repository at this point in the history
  • Loading branch information
sachac committed Jun 21, 2017
1 parent 6ac556c commit ed24907
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 0 deletions.
3 changes: 3 additions & 0 deletions app/models/record.rb
Expand Up @@ -105,6 +105,9 @@ def next_activity
# Added guard for double-entry
self.next.activities.where('(timestamp != end_timestamp OR end_timestamp IS NULL)').first
end
def calculated_duration(provided_start_timestamp = nil, provided_end_timestamp = Time.zone.now)
return [Time.zone.now, provided_end_timestamp, self.end_timestamp || Time.zone.now].min - [self.timestamp, provided_start_timestamp || self.timestamp].max
end
def self.recalculate_durations(user, start_time = nil, end_time = nil)
span = user.records
span = span.where('timestamp >= ?', start_time) if start_time
Expand Down
26 changes: 26 additions & 0 deletions spec/models/record_spec.rb
Expand Up @@ -121,6 +121,32 @@
expect(r2.reload.end_timestamp.to_s).to eq r1.timestamp.to_s
end
end
describe '#duration' do
before :all do
Timecop.freeze
@u = FactoryGirl.create(:confirmed_user)
@c = FactoryGirl.create(:record_category, user: @u, category_type: 'activity')
end
after :all do
Timecop.return
end
it 'reports proper duration if the ending timestamp is set' do
r1 = FactoryGirl.create(:record, user: @u, record_category: @c, timestamp: Time.zone.now - 2.hours, end_timestamp: Time.zone.now - 1.hour)
r1.calculated_duration.should == 1.hour
end
it 'truncates to current timestamp if the ending timestamp is not set' do
r1 = FactoryGirl.create(:record, user: @u, record_category: @c, timestamp: Time.zone.now - 2.hours)
r1.calculated_duration.should == 2.hours
end
it 'truncates to provided start time and end time' do
r1 = FactoryGirl.create(:record, user: @u, record_category: @c, timestamp: Time.zone.now - 2.hours)
r1.calculated_duration(Time.zone.now - 1.hour, Time.zone.now - 30.minutes).should == 30.minutes
end
it "stays within the activity's bounds" do
r1 = FactoryGirl.create(:record, user: @u, record_category: @c, timestamp: Time.zone.now - 2.hours)
r1.calculated_duration(Time.zone.now - 4.hour, Time.zone.now + 30.minutes).should == 2.hours
end
end
describe '.recalculate_durations' do
it "fixes all the durations" do
u = FactoryGirl.create(:confirmed_user)
Expand Down

0 comments on commit ed24907

Please sign in to comment.