{"id":13994862,"url":"https://github.com/railsware/workflow","last_synced_at":"2025-07-22T21:31:00.587Z","repository":{"id":56890745,"uuid":"2052641","full_name":"railsware/workflow","owner":"railsware","description":"Like acts as state machine (aasm), but _way_ better (it's in Ruby too!)","archived":false,"fork":true,"pushed_at":"2011-07-15T11:14:11.000Z","size":434,"stargazers_count":1,"open_issues_count":0,"forks_count":0,"subscribers_count":13,"default_branch":"master","last_synced_at":"2025-06-06T09:49:36.157Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":"http://www.geekq.net/workflow/","language":"Ruby","has_issues":false,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":"geekq/workflow","license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/railsware.png","metadata":{"files":{"readme":"README.markdown","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}},"created_at":"2011-07-15T10:59:29.000Z","updated_at":"2023-05-24T10:12:28.000Z","dependencies_parsed_at":null,"dependency_job_id":null,"html_url":"https://github.com/railsware/workflow","commit_stats":null,"previous_names":[],"tags_count":0,"template":false,"template_full_name":null,"purl":"pkg:github/railsware/workflow","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/railsware%2Fworkflow","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/railsware%2Fworkflow/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/railsware%2Fworkflow/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/railsware%2Fworkflow/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/railsware","download_url":"https://codeload.github.com/railsware/workflow/tar.gz/refs/heads/master","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/railsware%2Fworkflow/sbom","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":265424967,"owners_count":23762887,"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":[],"created_at":"2024-08-09T14:03:09.156Z","updated_at":"2025-07-22T21:31:00.305Z","avatar_url":"https://github.com/railsware.png","language":"Ruby","funding_links":[],"categories":["Ruby"],"sub_categories":[],"readme":"What 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    class 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\n    end\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    article = Article.new\n    article.accepted? # =\u003e false\n    article.new? # =\u003e true\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\nNow we can call the submit event, which transitions to the\n\u003ctt\u003e:awaiting_review\u003c/tt\u003e state:\n\n    article.submit!\n    article.awaiting_review? # =\u003e true\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\nInstallation\n------------\n\n    gem install workflow\n\nAlternatively you can just download the lib/workflow.rb and put it in\nthe lib folder of your Rails or Ruby application.\n\n\nRuby 1.9\n--------\n\nWorkflow gem does not work with some (but very widespread) Ruby 1.9\nbuilds due to a known bug in Ruby 1.9. Either \n\n* use newer ruby build, 1.9.2-p136 and -p180 tested to work\n* or compile your Ruby 1.9 from source \n* or [comment out some lines in workflow](http://github.com/geekq/workflow/issues#issue/6)\n(reduces functionality).\n\nExamples\n--------\n\nAfter installation or downloading of 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\nTransition event handler\n------------------------\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    class Article\n      def reject\n        puts 'sending email to the author explaining the reason...'\n      end\n    end\n\n`article.review!; article.reject!` will cause a state transition, persist the new state\n(if integrated with ActiveRecord) and invoke this user defined reject\nmethod.\n\nYou can also define event handler accepting/requiring additional\narguments:\n\n    class Article\n      def review(reviewer = '')\n        puts \"[#{reviewer}] is now reviewing the article\"\n      end\n    end\n\n    article2 = Article.new\n    article2.submit!\n    article2.review!('Homer Simpson') # =\u003e [Homer Simpson] is now reviewing the article\n\n\n### The old, deprecated way\n\nThe old way, using a block is still supported but deprecated:\n\n    event :review, :transitions_to =\u003e :being_reviewed do |reviewer|\n      # store the reviewer\n    end\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      \n\nIntegration with ActiveRecord\n-----------------------------\n\nWorkflow library can handle the state persistence fully automatically. You\nonly need to define a string field on the table called `workflow_state`\nand include the workflow mixin in your model class as usual:\n\n    class Order \u003c ActiveRecord::Base\n      include Workflow\n      workflow do\n        # list states and transitions here\n      end\n    end\n\nOn a database record loading all the state check methods e.g.\n`article.state`, `article.awaiting_review?` are immediately available.\nFor new records or if the workflow_state field is not set the state\ndefaults to the first state declared in the workflow specification. In\nour example it is `:new`, so `Article.new.new?` returns true and\n`Article.new.approved?` returns false.\n\nAt the end of a successful state transition like `article.approve!` the\nnew state is immediately saved in the database.\n\nYou can change this behaviour by overriding `persist_workflow_state`\nmethod.\n\n\n### Custom workflow database column\n\n[meuble](http://imeuble.info/) contributed a solution for using\ncustom persistence column easily, e.g. for a legacy database schema:\n\n    class LegacyOrder \u003c ActiveRecord::Base\n      include Workflow\n      \n      workflow_column :foo_bar # use this legacy database column for\n                               # persistence\n    end\n\n\n\n### Single table inheritance\n\nSingle table inheritance is also supported. Descendant classes can either\ninherit the workflow definition from the parent or override with its own\ndefinition.\n\nCustom workflow state persistence\n---------------------------------\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\n[Tim Lossen](http://tim.lossen.de/) implemented support \nfor [remodel](http://github.com/tlossen/remodel) / [redis](http://github.com/antirez/redis) \nkey-value store.\n\nIntegration with CouchDB\n------------------------\n\nWe are using the compact [couchtiny library](http://github.com/geekq/couchtiny)\nhere. But the implementation would look similar for the popular\ncouchrest library.\n\n    require 'couchtiny'\n    require 'couchtiny/document'\n    require 'workflow'\n\n    class 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\n    end\n\nPlease also have a look at \n[the full source code](http://github.com/geekq/workflow/blob/master/test/couchtiny_example.rb).\n\nIntegration with Mongoid\n------------------------\n\nYou can integrate with Mongoid following the example above for CouchDB, but there is a gem that does that for you (and includes extensive tests):\n[workflow_on_mongoid](http://github.com/bowsersenior/workflow_on_mongoid)\n\nAccessing your workflow specification\n-------------------------------------\n\nYou can easily reflect on workflow specification programmatically - for\nthe whole class or for the current object. Examples:\n\n    article2.current_state.events # lists possible events from here\n    article2.current_state.events[:reject].transitions_to # =\u003e :rejected\n\n    Article.workflow_spec.states.keys\n    #=\u003e [:rejected, :awaiting_review, :being_reviewed, :accepted, :new]\n\n    Article.workflow_spec.state_names\n    #=\u003e [:rejected, :awaiting_review, :being_reviewed, :accepted, :new]\n\n    # list all events for all states\n    Article.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    class 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\n    end\n    puts MyProcess.workflow_spec.states[:supplemental].meta[:importance] # =\u003e 1\n\nThe workflow library itself uses this feature to tweak the graphical\nrepresentation of the workflow. See below.\n \n\nAdvanced transition hooks\n-------------------------\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    workflow 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\n    end\n\nPlease also have a look at the [advanced end to end\nexample][advanced_hooks_and_validation_test].\n\n[advanced_hooks_and_validation_test]: http://github.com/geekq/workflow/blob/master/test/advanced_hooks_and_validation_test.rb\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    def reject(reason)\n      halt! 'We do not reject articles unless the reason is important' \\\n        unless reason =~ /important/i\n    end\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\n    * on_entry\n    * after_transition\n\n\nMultiple Workflows\n------------------\n\nI am frequently asked if it's possible to represent multiple \"workflows\"\nin an ActiveRecord class. \n\nThe solution depends on your business logic and how you want to\nstructure your implementation.\n\n### Use Single Table Inheritance\n\nOne solution can be to do it on the class level and use a class\nhierarchy. You can use [single table inheritance][STI] so there is only\nsingle `orders` table in the database. Read more in the chapter \"Single\nTable Inheritance\" of the [ActiveRecord documentation][ActiveRecord].\nThen you define your different classes:\n\n    class Order \u003c ActiveRecord::Base\n      include Workflow\n    end\n\n    class SmallOrder \u003c Order\n      workflow do\n        # workflow definition for small orders goes here\n      end\n    end\n\n    class BigOrder \u003c Order\n      workflow do\n        # workflow for big orders, probably with a longer approval chain\n      end\n    end\n\n\n### Individual workflows for objects\n\nAnother solution would be to connect different workflows to object\ninstances via metaclass, e.g.\n\n    # Load an object from the database\n    booking = Booking.find(1234)\n\n    # Now define a workflow - exclusively for this object,\n    # probably depending on some condition or database field\n    if # some condition\n      class \u003c\u003c booking\n        include Workflow\n        workflow do\n          state :state1\n          state :state2\n        end\n      end\n    # if some other condition, use a different workflow\n\nYou can also encapsulate this in a class method or even put in some\nActiveRecord callback. Please also have a look at [the full working\nexample][multiple_workflow_test]!\n\n[STI]: http://www.martinfowler.com/eaaCatalog/singleTableInheritance.html\n[ActiveRecord]: http://api.rubyonrails.org/classes/ActiveRecord/Base.html\n[multiple_workflow_test]: http://github.com/geekq/workflow/blob/master/test/multiple_workflows_test.rb\n\n\nDocumenting with diagrams\n-------------------------\n\nYou can generate a graphical representation of your workflow for\ndocumentation purposes. S. Workflow::create_workflow_diagram.\n\n\nEarlier versions\n----------------\n\nThe `workflow` library was originally written by Ryan Allen.\n\nThe version 0.3 was almost completely (including ActiveRecord\nintegration, API for accessing workflow specification, \nmethod_missing free implementation) rewritten by Vladimir Dobriakov\nkeeping the original workflow DSL spirit.\n\n\nMigration from the original Ryan's library\n------------------------------------------\n\nCredit: Michael (rockrep)\n\nAccessing workflow specification\n\n    my_instance.workflow # old\n    MyClass.workflow_spec # new\n\nAccessing states, events, meta, e.g.\n\n    my_instance.workflow.states(:some_state).events(:some_event).meta[:some_meta_tag] # old\n    MyClass.workflow_spec.states[:some_state].events[:some_event].meta[:some_meta_tag] # new\n\nCausing state transitions\n\n    my_instance.workflow.my_event # old\n    my_instance.my_event! # new\n\nwhen using both a block and a callback method for an event, the block executes prior to the callback\n\n\nChangelog\n---------\n\n### New in the version 0.8.0\n\n* check if a certain transition possible from the current state with\n  `can_....?`\n* fix workflow_state persistence for multiple_workflows example\n* add before_transition and after_transition hooks as suggested by\n  [kasperbn](https://github.com/kasperbn)\n\n### New in the version 0.7.0\n\n* fix issue#10 Workflow::create_workflow_diagram documentation and path\n  escaping\n* fix issue#7 workflow_column does not work STI (single table\n  inheritance) ActiveRecord models\n* fix issue#5 Diagram generation fails for models in modules\n\n### New in the version 0.6.0\n\n* enable multiple workflows by connecting workflow to object instances\n  (using metaclass) instead of connecting to a class, s. \"Multiple\n  Workflows\" section\n\n### New in the version 0.5.0\n\n* fix issue#3 change the behaviour of halt! to immediately raise an\n  exception. See also http://github.com/geekq/workflow/issues/#issue/3\n\n### New in the version 0.4.0\n\n* completely rewritten the documentation to match my branch\n* switch to [jeweler][] for building gems\n* use [gemcutter][] for gem distribution\n* every described feature is backed up by an automated test\n\n[jeweler]: http://github.com/technicalpickles/jeweler\n[gemcutter]: http://gemcutter.org/gems/workflow\n\n### New in the version 0.3.0\n\nIntermixing of transition graph definition (states, transitions)\non the one side and implementation of the actions on the other side\nfor a bigger state machine can introduce clutter.\n\nTo reduce this clutter it is now possible to use state entry- and \nexit- hooks defined through a naming convention. For example, if there\nis a state :pending, then instead of using a\nblock:\n\n    state :pending do\n      on_entry do\n        # your implementation here\n      end\n    end\n\nyou can hook in by defining method \n\n    def on_pending_exit(new_state, event, *args)\n      # your implementation here\n    end\n\nanywhere in your class. You can also use a simpler function signature\nlike `def on_pending_exit(*args)` if your are not interested in\narguments.  Please note: `def on_pending_exit()` with an empty list\nwould not work.\n\nIf both a function with a name according to naming convention and the \non_entry/on_exit block are given, then only on_entry/on_exit block is used.\n\n\nSupport\n-------\n\n### Reporting bugs\n\n\u003chttp://github.com/geekq/workflow/issues\u003e\n\n\nAbout\n-----\n\nAuthor: Vladimir Dobriakov, \u003chttp://www.innoq.com/blog/vd\u003e, \u003chttp://blog.geekq.net/\u003e\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\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Frailsware%2Fworkflow","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Frailsware%2Fworkflow","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Frailsware%2Fworkflow/lists"}