{"id":13484597,"url":"https://github.com/geekq/workflow","last_synced_at":"2025-05-14T01:03:33.082Z","repository":{"id":487089,"uuid":"113141","full_name":"geekq/workflow","owner":"geekq","description":"Ruby finite-state-machine-inspired API for modeling workflow","archived":false,"fork":false,"pushed_at":"2024-05-17T08:19:28.000Z","size":524,"stargazers_count":1732,"open_issues_count":10,"forks_count":208,"subscribers_count":41,"default_branch":"develop","last_synced_at":"2024-05-17T16:32:03.924Z","etag":null,"topics":["aasm","dsl","ruby","state-machine"],"latest_commit_sha":null,"homepage":"","language":"Ruby","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/geekq.png","metadata":{"files":{"readme":"README.adoc","changelog":null,"contributing":null,"funding":null,"license":"MIT-LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2009-01-23T11:52:34.000Z","updated_at":"2024-05-29T19:46:01.782Z","dependencies_parsed_at":"2024-05-29T19:45:55.755Z","dependency_job_id":null,"html_url":"https://github.com/geekq/workflow","commit_stats":{"total_commits":374,"total_committers":40,"mean_commits":9.35,"dds":"0.47058823529411764","last_synced_commit":"ba6946ba6711e2d255cc2fd5d28e6af3add3df36"},"previous_names":[],"tags_count":8,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/geekq%2Fworkflow","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/geekq%2Fworkflow/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/geekq%2Fworkflow/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/geekq%2Fworkflow/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/geekq","download_url":"https://codeload.github.com/geekq/workflow/tar.gz/refs/heads/develop","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":247962460,"owners_count":21024862,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["aasm","dsl","ruby","state-machine"],"created_at":"2024-07-31T17:01:26.862Z","updated_at":"2025-04-09T02:11:11.290Z","avatar_url":"https://github.com/geekq.png","language":"Ruby","readme":":doctype: book\n:toc: macro\n:toclevels: 1\n:sectlinks:\n:idprefix:\n\n# Workflow\n\nimage:https://img.shields.io/gem/v/workflow.svg[link=https://rubygems.org/gems/workflow]\nimage:https://github.com/geekq/workflow/actions/workflows/test.yml/badge.svg[link=https://github.com/geekq/workflow/actions/workflows/test.yml]\nimage:https://codeclimate.com/github/geekq/workflow/badges/gpa.svg[link=https://codeclimate.com/github/geekq/workflow]\nimage:https://codeclimate.com/github/geekq/workflow/badges/coverage.svg[link=https://codeclimate.com/github/geekq/workflow/coverage]\n\nNote: you can find documentation for specific workflow rubygem versions\nat http://rubygems.org/gems/workflow : select a version (optional,\ndefault is latest release), click \"Documentation\" link. When reading on\ngithub.com, the README refers to the upcoming release.\n\ntoc::[]\n\nWhat is workflow?\n-----------------\n\nWorkflow is a finite-state-machine-inspired API for modeling and\ninteracting with what we tend to refer to as 'workflow'.\n\nA lot of business modeling tends to involve workflow-like concepts, and\nthe aim of this library is to make the expression of these concepts as\nclear as possible, using similar terminology as found in state machine\ntheory.\n\nSo, a workflow has a state. It can only be in one state at a time. When\na workflow changes state, we call that a transition. Transitions occur\non an event, so events cause transitions to occur. Additionally, when an\nevent fires, other arbitrary code can be executed, we call those actions.\nSo any given state has a bunch of events, any event in a state causes a\ntransition to another state and potentially causes code to be executed\n(an action). We can hook into states when they are entered, and exited\nfrom, and we can cause transitions to fail (guards), and we can hook in\nto every transition that occurs ever for whatever reason we can come up\nwith.\n\nNow, all that's a mouthful, but we'll demonstrate the API bit by bit\nwith a real-ish world example.\n\nLet's say we're modeling article submission from journalists. An article\nis written, then submitted. When it's submitted, it's awaiting review.\nSomeone reviews the article, and then either accepts or rejects it.\nHere is the expression of this workflow using the API:\n\n```rb\nclass Article\n  include Workflow\n  workflow do\n    state :new do\n      event :submit, :transitions_to =\u003e :awaiting_review\n    end\n    state :awaiting_review do\n      event :review, :transitions_to =\u003e :being_reviewed\n    end\n    state :being_reviewed do\n      event :accept, :transitions_to =\u003e :accepted\n      event :reject, :transitions_to =\u003e :rejected\n    end\n    state :accepted\n    state :rejected\n  end\nend\n```\n\nNice, isn't it!\n\nNote: the first state in the definition (`:new` in the example, but you\ncan name it as you wish) is used as the initial state - newly created\nobjects start their life cycle in that state.\n\nLet's create an article instance and check in which state it is:\n\n```rb\narticle = Article.new\narticle.accepted? # =\u003e false\narticle.new? # =\u003e true\n```\n\nYou can also access the whole `current_state` object including the list\nof possible events and other meta information:\n\n    article.current_state\n    =\u003e #\u003cWorkflow::State:0x7f1e3d6731f0 @events={\n      :submit=\u003e#\u003cWorkflow::Event:0x7f1e3d6730d8 @action=nil,\n        @transitions_to=:awaiting_review, @name=:submit, @meta={}\u003e},\n      name:new, meta{}\n\nYou can also check, whether a state comes before or after another state (by the\norder they were defined):\n\n```rb\narticle.current_state # =\u003e being_reviewed\narticle.current_state \u003c :accepted # =\u003e true\narticle.current_state \u003e= :accepted # =\u003e false\narticle.current_state.between? :awaiting_review, :rejected # =\u003e true\n```\n\nNow we can call the submit event, which transitions to the\n`:awaiting_review` state:\n\n```rb\narticle.submit!\narticle.awaiting_review? # =\u003e true\n```\n\nEvents are actually instance methods on a workflow, and depending on the\nstate you're in, you'll have a different set of events used to\ntransition to other states.\n\nIt is also easy to check, if a certain transition is possible from the\ncurrent state . `article.can_submit?` checks if there is a `:submit`\nevent (transition) defined for the current state.\n\n\nGetting started\n---------------\n\n=== Installation\n\n```sh\ngem install workflow\n```\n\n**Important**: If you're interested in graphing your workflow state machine, you will also need to\ninstall the `activesupport` and `ruby-graphviz` gems.\n\nVersions up to and including 1.0.0 are also available as a single file download -\nlink:https://github.com/geekq/workflow/blob/v1.0.0/lib/workflow.rb[lib/workflow.rb file].\n\n\n=== Examples\n\nAfter installation or downloading the library you can easily try out\nall the example code from this README in irb.\n\n    $ irb\n    require 'rubygems'\n    require 'workflow'\n\nNow just copy and paste the source code from the beginning of this README\nfile snippet by snippet and observe the output.\n\n\n### Transition event handler\n\nThe best way is to use convention over configuration and to define a\nmethod with the same name as the event. Then it is automatically invoked\nwhen event is raised. For the Article workflow defined earlier it would\nbe:\n\n```rb\nclass Article\n  def reject\n    puts 'sending email to the author explaining the reason...'\n  end\nend\n```\n\n`article.review!; article.reject!` will cause state transition to\n`being_reviewed` state, persist the new state (if integrated with\nActiveRecord), invoke this user defined `reject` method and finally\npersist the `rejected` state.\n\nNote: on successful transition from one state to another the workflow\ngem immediately persists the new workflow state with `update_column()`,\nbypassing any ActiveRecord callbacks including `updated_at` update.\nThis way it is possible to deal with the validation and to save the\npending changes to a record at some later point instead of the moment\nwhen transition occurs.\n\nYou can also define event handler accepting/requiring additional\narguments:\n\n```rb\nclass Article\n  def review(reviewer = '')\n    puts \"[#{reviewer}] is now reviewing the article\"\n  end\nend\n\narticle2 = Article.new\narticle2.submit!\narticle2.review!('Homer Simpson') # =\u003e [Homer Simpson] is now reviewing the article\n```\n\nAlternative way is to use a block (only recommended for short event\nimplementation without further code nesting):\n\n```rb\nevent :review, :transitions_to =\u003e :being_reviewed do |reviewer|\n  # store the reviewer\nend\n```\n\nWe've noticed, that mixing the list of events and states with the blocks\ninvoked for particular transitions leads to a bumpy and poorly readable code\ndue to a deep nesting. We tried (and dismissed) lambdas for this. Eventually\nwe decided to invoke an optional user defined callback method with the same\nname as the event (convention over configuration) as explained before.\n\nState persistence\n-----------------\n\n=== ActiveRecord\n\nNote: Workflow 2.0 is a major refactoring for the `worklow` library.\nIf your application suddenly breaks after the workflow 2.0 release, you've\nprobably got your Gemfile wrong ;-). workflow uses\nhttps://guides.rubygems.org/patterns/#semantic-versioning[semantic versioning].\nFor highest compatibility please reference the desired major+minor version.\n\nNote on ActiveRecord/Rails 4.\\*, 5.\\* Support:\n\nSince integration with ActiveRecord makes over 90% of the issues and\nmaintenance effort, and also to allow for an independent (faster) release cycle\nfor Rails support, starting with workflow **version 2.0** in January 2019 the\nsupport for ActiveRecord (4.\\*, 5.\\* and newer) has been extracted into a separate\ngem. Read at\nhttps://github.com/geekq/workflow-activerecord[workflow-activerecord], how to\ninclude the right gem.\n\nTo use legacy built-in ActiveRecord 2.3 - 4.* support, reference Workflow 1.2 in\nyour Gemfile:\n\n    gem 'workflow', '~\u003e 1.2'\n\n\n=== Custom workflow state persistence\n\nIf you do not use a relational database and ActiveRecord, you can still\nintegrate the workflow very easily. To implement persistence you just\nneed to override `load_workflow_state` and\n`persist_workflow_state(new_value)` methods. Next section contains an example for\nusing CouchDB, a document oriented database.\n\nhttp://tim.lossen.de/[Tim Lossen] implemented support\nfor http://github.com/tlossen/remodel[remodel] / http://github.com/antirez/redis[redis]\nkey-value store.\n\n=== Integration with CouchDB\n\nWe are using the compact http://github.com/geekq/couchtiny[couchtiny library]\nhere. But the implementation would look similar for the popular\ncouchrest library.\n\n```rb\nrequire 'couchtiny'\nrequire 'couchtiny/document'\nrequire 'workflow'\n\nclass User \u003c CouchTiny::Document\n  include Workflow\n  workflow do\n    state :submitted do\n      event :activate_via_link, :transitions_to =\u003e :proved_email\n    end\n    state :proved_email\n  end\n\n  def load_workflow_state\n    self[:workflow_state]\n  end\n\n  def persist_workflow_state(new_value)\n    self[:workflow_state] = new_value\n    save!\n  end\nend\n```\n\nPlease also have a look at\nhttp://github.com/geekq/workflow/blob/develop/test/couchtiny_example.rb[the full source code].\n\n\n=== Adapters to support other databases\n\nI get a lot of requests to integrate persistence support for different\ndatabases, object-relational adapters, column stores, document\ndatabases.\n\nTo enable highest possible quality, avoid too many dependencies and to\navoid unneeded maintenance burden on the `workflow` core it is best to\nimplement such support as a separate gem.\n\nOnly support for the ActiveRecord will remain for the foreseeable\nfuture. So Rails beginners can expect `workflow` to work with Rails out\nof the box. Other already included adapters stay for a while but should\nbe extracted to separate gems.\n\nIf you want to implement support for your favorite ORM mapper or your\nfavorite NoSQL database, you just need to implement a module which\noverrides the persistence methods `load_workflow_state` and\n`persist_workflow_state`. Example:\n\n```rb\nmodule Workflow\n  module SuperCoolDb\n    module InstanceMethods\n      def load_workflow_state\n        # Load and return the workflow_state from some storage.\n        # You can use self.class.workflow_column configuration.\n      end\n\n      def persist_workflow_state(new_value)\n        # save the new_value workflow state\n      end\n    end\n\n    module ClassMethods\n      # class methods of your adapter go here\n    end\n\n    def self.included(klass)\n      klass.send :include, InstanceMethods\n      klass.extend ClassMethods\n    end\n  end\nend\n```\n\nThe user of the adapter can use it then as:\n\n```rb\nclass Article\n  include Workflow\n  include Workflow:SuperCoolDb\n  workflow do\n    state :submitted\n    # ...\n  end\nend\n```\n\nI can then link to your implementation from this README. Please let me\nalso know, if you need any interface beyond `load_workflow_state` and\n`persist_workflow_state` methods to implement an adapter for your\nfavorite database.\n\nAdvanced usage\n--------------\n\n### Conditional event transitions\n\nConditions can be a \"method name symbol\" with a corresponding instance method, a `proc` or `lambda` which are added to events, like so:\n\n```rb\nstate :off\n  event :turn_on, :transition_to =\u003e :on,\n                  :if =\u003e :sufficient_battery_level?\n\n  event :turn_on, :transition_to =\u003e :low_battery,\n                  :if =\u003e proc { |device| device.battery_level \u003e 0 }\nend\n\n# corresponding instance method\ndef sufficient_battery_level?\n  battery_level \u003e 10\nend\n```\n\nWhen calling a `device.can_\u003cfire_event\u003e?` check, or attempting a `device.\u003cevent\u003e!`, each event is checked in turn:\n\n* With no `:if` check, proceed as usual.\n* If an `:if` check is present, proceed if it evaluates to true, or drop to the next event.\n* If you've run out of events to check (eg. `battery_level == 0`), then the transition isn't possible.\n\nYou can also pass additional arguments, which can be evaluated by :if methods or procs. See examples in\nlink:test/conditionals_test.rb#L45[conditionals_test.rb]\n\n### Advanced transition hooks\n\n#### on_entry/on_exit\n\nWe already had a look at the declaring callbacks for particular workflow\nevents. If you would like to react to all transitions to/from the same state\nin the same way you can use the on_entry/on_exit hooks. You can either define it\nwith a block inside the workflow definition or through naming\nconvention, e.g. for the state :pending just define the method\n`on_pending_exit(new_state, event, *args)` somewhere in your class.\n\n#### on_transition\n\nIf you want to be informed about everything happening everywhere, e.g. for\nlogging then you can use the universal `on_transition` hook:\n\n```rb\nworkflow do\n  state :one do\n    event :increment, :transitions_to =\u003e :two\n  end\n  state :two\n  on_transition do |from, to, triggering_event, *event_args|\n    Log.info \"#{from} -\u003e #{to}\"\n  end\nend\n```\n\n#### on_error\n\nIf you want to do custom exception handling internal to workflow, you can define an `on_error` hook in your workflow.\nFor example:\n\n```rb\nworkflow do\n  state :first do\n    event :forward, :transitions_to =\u003e :second\n  end\n  state :second\n\n  on_error do |error, from, to, event, *args|\n    Log.info \"Exception(#{error.class}) on #{from} -\u003e #{to}\"\n  end\nend\n```\n\nIf forward! results in an exception, `on_error` is invoked and the workflow stays in a 'first' state.  This capability\nis particularly useful if your errors are transient and you want to queue up a job to retry in the future without\naffecting the existing workflow state.\n\n### Guards\n\nIf you want to halt the transition conditionally, you can just raise an\nexception in your [transition event handler](#transition_event_handler).\nThere is a helper called `halt!`, which raises the\nWorkflow::TransitionHalted exception. You can provide an additional\n`halted_because` parameter.\n\n```rb\ndef reject(reason)\n  halt! 'We do not reject articles unless the reason is important' \\\n    unless reason =~ /important/i\nend\n```\n\nThe traditional `halt` (without the exclamation mark) is still supported\ntoo. This just prevents the state change without raising an\nexception.\n\nYou can check `halted?` and `halted_because` values later.\n\n### Hook order\n\nThe whole event sequence is as follows:\n\n    * before_transition\n    * event specific action\n    * on_transition (if action did not halt)\n    * on_exit\n    * PERSIST WORKFLOW STATE (i.e. transition) or on_error\n    * on_entry\n    * after_transition\n\n\n### Accessing your workflow specification\n\nYou can easily reflect on workflow specification programmatically - for\nthe whole class or for the current object. Examples:\n\n```rb\narticle2.current_state.events # lists possible events from here\narticle2.current_state.events[:reject].transitions_to # =\u003e :rejected\n\nArticle.workflow_spec.states.keys\n#=\u003e [:rejected, :awaiting_review, :being_reviewed, :accepted, :new]\n\nArticle.workflow_spec.state_names\n#=\u003e [:rejected, :awaiting_review, :being_reviewed, :accepted, :new]\n\n# list all events for all states\nArticle.workflow_spec.states.values.collect \u0026:events\n```\n\nYou can also store and later retrieve additional meta data for every\nstate and every event:\n\n```rb\nclass MyProcess\n  include Workflow\n  workflow do\n    state :main, :meta =\u003e {:importance =\u003e 8}\n    state :supplemental, :meta =\u003e {:importance =\u003e 1}\n  end\nend\nputs MyProcess.workflow_spec.states[:supplemental].meta[:importance] # =\u003e 1\n```\n\nThe workflow library itself uses this feature to tweak the graphical\nrepresentation of the workflow. See below.\n\n\n### Defining workflow dynamically from JSON\n\nFor an advance example please see\nlink:https://github.com/geekq/workflow/blob/develop/test/workflow_from_json_test.rb[workflow_from_json_test.rb].\n\n\n### Compose workflow definition with `include`\n\nIn case you have very extensive workflow definition or would like to reuse\nworkflow definition for different classes, you can include parts like in\nthe link:https://github.com/geekq/workflow/blob/develop/test/main_test.rb#L95-L110[`including a child workflow definition` example].\n\nDocumenting with diagrams\n-------------------------\n\nYou can generate a graphical representation of the workflow for\na particular class for documentation purposes.\nUse `Workflow::create_workflow_diagram(class)` in your rake task like:\n\n```rb\nnamespace :doc do\n  desc \"Generate a workflow graph for a model passed e.g. as 'MODEL=Order'.\"\n  task :workflow =\u003e :environment do\n    require 'workflow/draw'\n    Workflow::Draw::workflow_diagram(ENV['MODEL'].constantize)\n  end\nend\n```\n\nSupport, Participation\n----------------------\n\n### Reporting bugs\n\n\u003chttp://github.com/geekq/workflow/issues\u003e\n\n### Development Setup\n\n```sh\nsudo apt-get install graphviz # Linux\nbrew install graphviz # Mac OS\ncd workflow\ngem install bundler\nbundle install\n# run all the tests\nbundle exec rake test\n```\n\n### Check list for you pull request\n\n* [ ] unit tests for the new behavior provided: new tests fail without you change, all tests succeed with your change\n* [ ] documentation update included\n\n### Other 3rd party libraries\n\nhttps://github.com/kwent/active_admin-workflow[ActiveAdmin-Workflow] - is an\nintegration with https://github.com/activeadmin/activeadmin[ActiveAdmin].\n\n### About\n\nAuthor: Vladimir Dobriakov, \u003chttps://infrastructure-as-code.de\u003e\n\nCopyright (c) 2010-2024 Vladimir Dobriakov and Contributors\n\nCopyright (c) 2008-2009 Vodafone\n\nCopyright (c) 2007-2008 Ryan Allen, FlashDen Pty Ltd\n\nBased on the work of Ryan Allen and Scott Barron\n\nLicensed under MIT license, see the MIT-LICENSE file.\n","funding_links":[],"categories":["State Machines","Ruby"],"sub_categories":[],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fgeekq%2Fworkflow","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fgeekq%2Fworkflow","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fgeekq%2Fworkflow/lists"}