Skip to content

Commit

Permalink
ignore timestamps if they have been set earlier
Browse files Browse the repository at this point in the history
  • Loading branch information
svenfuchs committed Apr 26, 2016
1 parent 75f710d commit 952c87c
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 12 deletions.
13 changes: 5 additions & 8 deletions lib/simple_states/event.rb
Expand Up @@ -30,20 +30,17 @@ def run_callbacks(type, obj, data)
end

def set_attrs(obj, data)
target_state_attr = "#{target_state(data)}_at"
attrs = { :"#{target_state_attr}" => Time.now.utc }.merge(data)
attrs.each do |key, value|
set_attr(obj, key, value) if set_timestamp?(key.to_s, target_state_attr)
end
attrs = { :"#{target_state(data)}_at" => Time.now.utc }.merge(data)
attrs.each { |key, value| set_attr(obj, key, value) }
obj.state = target_state(data)
end

def set_attr(obj, key, value)
obj.send(:"#{key}=", value) if obj.respond_to?(:"#{key}=")
obj.send(:"#{key}=", value) if obj.respond_to?(:"#{key}=") and not has_timestamp?(obj, key)
end

def set_timestamp?(key, target_state_attr)
key == target_state_attr || key == "finished_at" || !key.end_with?('at')
def has_timestamp?(obj, key)
key.to_s.end_with?('_at') && obj.respond_to?(key) && obj.send(key)
end

def ordered?(obj, data)
Expand Down
20 changes: 16 additions & 4 deletions spec/events_spec.rb
Expand Up @@ -40,10 +40,22 @@
end

describe 'ignores timestamp' do
describe 'when started_at timestamp is passed on a finish event' do
let(:attrs) { { finished_at: now - 50, started_at: now - 60, state: "passed" } }
it { expect { obj.finish(attrs) }.to change { obj.finished_at }.to(attrs[:finished_at]) }
it { expect { obj.finish(attrs) }.to_not change { obj.started_at }}
describe 'when started_at had been set earlier' do
let(:attrs) { { started_at: now - 60, finished_at: now - 50, state: "passed" } }
let(:early) { now - 55 }
before { obj.started_at = early }
before { obj.finish(attrs) }
it { expect(obj.started_at).to eq early }
it { expect(obj.finished_at).to eq attrs[:finished_at] }
end

describe 'when finished_at had been set earlier' do
let(:attrs) { { started_at: now - 60, finished_at: now - 50, state: "passed" } }
let(:early) { now - 45 }
before { obj.finished_at = early }
before { obj.finish(attrs) }
it { expect(obj.started_at).to eq attrs[:started_at] }
it { expect(obj.finished_at).to eq early }
end
end

Expand Down

0 comments on commit 952c87c

Please sign in to comment.