Skip to content

Commit

Permalink
Merge pull request joker1007#23 from wanabe/execute-now-for-unpersisted
Browse files Browse the repository at this point in the history
`#execute_now` for unpersisted model
  • Loading branch information
joker1007 authored Mar 23, 2020
2 parents 69a056e + 81915d3 commit e03e0a6
Show file tree
Hide file tree
Showing 2 changed files with 41 additions and 1 deletion.
7 changes: 6 additions & 1 deletion lib/crono_trigger/schedulable.rb
Original file line number Diff line number Diff line change
Expand Up @@ -223,7 +223,11 @@ def crono_trigger_lock!(**attributes)
crono_trigger_column_name(:locked_by) => CronoTrigger.config.worker_id
}.merge(attributes)
merge_updated_at_for_crono_trigger!(attributes)
update_columns(attributes)
if new_record?
self.attributes = attributes
else
update_columns(attributes)
end
end

def crono_trigger_unlock!
Expand Down Expand Up @@ -269,6 +273,7 @@ def crono_trigger_column_name(name)

def execute_now
crono_trigger_lock!(next_execute_at: Time.now)
save! if new_record?
do_execute
end

Expand Down
35 changes: 35 additions & 0 deletions spec/crono_trigger/schedulable_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,11 @@
started_at: Time.current.since(2.day),
).tap(&:activate_schedule!)
end
let(:new_notification) do
Notification.new(
started_at: Time.current,
)
end

describe "before_create callback" do
it "calculate_next_execute_at" do
Expand Down Expand Up @@ -518,6 +523,14 @@ def notification1.execute
notification1.crono_trigger_lock!(next_execute_at: next_execute_at)
expect(notification1.next_execute_at).to eq(next_execute_at)
end

it "lock even if unpersisted" do
expect(new_notification.locking?).to be_falsey
expect(new_notification.new_record?).to be_truthy
new_notification.crono_trigger_lock!
expect(new_notification.locking?).to be_truthy
expect(new_notification.new_record?).to be_truthy
end
end

describe "#assume_executing?" do
Expand Down Expand Up @@ -603,5 +616,27 @@ def notification1.execute
end
end
end

it "execute and save unpersisted model" do
Timecop.freeze(Time.utc(2017, 6, 18, 1, 15)) do
aggregate_failures do
expect(CronoTrigger::Models::Execution.count).to eq(0)
expect(Notification.results).to be_empty
expect(new_notification).to receive(:after)

expect {
new_notification.execute_now
}.to change { new_notification.execute_callback }.from(nil).to(:before)

expect(new_notification.persisted?).to be_truthy
expect(new_notification.next_execute_at).to be_nil
expect(new_notification.last_executed_at).to eq(Time.utc(2017, 6, 18, 1, 15))
expect(new_notification.execute_lock).to eq(0)
expect(Notification.results).to eq({new_notification.id => "executed"})
expect(CronoTrigger::Models::Execution.count).to eq(1)
expect(CronoTrigger::Models::Execution.last.status).to eq("completed")
end
end
end
end
end

0 comments on commit e03e0a6

Please sign in to comment.