Skip to content

Prevent setting to invalid state with update methods #58

Description

@pangdaxing23

I see there was some discussion about this issue in #49 , but it seems the validations did not make it into the master branch.

# job.rb
class Job < ApplicationRecord
  enum :status, {pending: 0, running: 1, done: 2, cancelled: 3} do
    event :run do
      transition [:pending] => :running
    end

    event :cancel do
      transition [:pending, :running] => :cancelled
    end

    event :finish do
      transition [:running] => :done
    end
  end
end
irb(main):001> job = Job.create!
=> #<Job:0x0000000107822e60 id: 1, status: "pending", created_at: Sun, 22 Sep 2024 15:35:34.179823000 UTC +00:00, updated_at: Sun, 22 Sep 2024 15:35:34.179823000 UTC +00:00>
irb(main):002> job.run!
=> true
irb(main):003> job.status
=> "running"
irb(main):004> job.finish!
=> true
irb(main):005> job.status
=> "done"
irb(main):006> job.cancel!
GEMPATH/stateful_enum-0.7.0/lib/stateful_enum/machine.rb:71:in `block (2 levels) in initialize': Invalid transition (RuntimeError)
irb(main):007> job.update status: :cancelled
=> true
irb(main):008> job.status
=> "cancelled"

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions