simply_fsm 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: aba0392debc9515f01b6b95bca88ed5c3a4aace120a3b725c4d1a840854a1725
4
+ data.tar.gz: 1d7883abe1ce6b0db890203293ea4f3ff2ab275fb876628daf07fb0f9ea087d6
5
+ SHA512:
6
+ metadata.gz: 9320692222abae9ec39bebf5b5594f023d97efecec721d400f6aacb5ed758cf0e02d23fc4e5845d604a0ec39682de16d7e919d8024ce69f762722cf134d1243b
7
+ data.tar.gz: c1552d33ce0b9e1d682e7e1d7cbbc7cd6ec59fbc4435d63582f67735f6a75cb0fe114910266624aee241f694aa77c2031634351466b798563981fc71f112ef71
data/.gitignore ADDED
@@ -0,0 +1,11 @@
1
+ /.bundle/
2
+ /.yardoc
3
+ /_yardoc/
4
+ /coverage/
5
+ /doc/
6
+ /pkg/
7
+ /spec/reports/
8
+ /tmp/
9
+
10
+ # rspec failure tracking
11
+ .rspec_status
data/.rspec ADDED
@@ -0,0 +1,3 @@
1
+ --format documentation
2
+ --color
3
+ --require spec_helper
data/.rubocop.yml ADDED
@@ -0,0 +1,13 @@
1
+ AllCops:
2
+ TargetRubyVersion: 2.7
3
+
4
+ Style/StringLiterals:
5
+ Enabled: true
6
+ EnforcedStyle: double_quotes
7
+
8
+ Style/StringLiteralsInInterpolation:
9
+ Enabled: true
10
+ EnforcedStyle: double_quotes
11
+
12
+ Layout/LineLength:
13
+ Max: 120
data/.ruby-version ADDED
@@ -0,0 +1 @@
1
+ 2.7
data/CHANGELOG.md ADDED
@@ -0,0 +1,5 @@
1
+ ## [Unreleased]
2
+
3
+ ## [0.1.0] - 2022-02-21
4
+
5
+ - Initial release supports finite state machine with event guards and failure handling
@@ -0,0 +1,84 @@
1
+ # Contributor Covenant Code of Conduct
2
+
3
+ ## Our Pledge
4
+
5
+ We as members, contributors, and leaders pledge to make participation in our community a harassment-free experience for everyone, regardless of age, body size, visible or invisible disability, ethnicity, sex characteristics, gender identity and expression, level of experience, education, socio-economic status, nationality, personal appearance, race, religion, or sexual identity and orientation.
6
+
7
+ We pledge to act and interact in ways that contribute to an open, welcoming, diverse, inclusive, and healthy community.
8
+
9
+ ## Our Standards
10
+
11
+ Examples of behavior that contributes to a positive environment for our community include:
12
+
13
+ * Demonstrating empathy and kindness toward other people
14
+ * Being respectful of differing opinions, viewpoints, and experiences
15
+ * Giving and gracefully accepting constructive feedback
16
+ * Accepting responsibility and apologizing to those affected by our mistakes, and learning from the experience
17
+ * Focusing on what is best not just for us as individuals, but for the overall community
18
+
19
+ Examples of unacceptable behavior include:
20
+
21
+ * The use of sexualized language or imagery, and sexual attention or
22
+ advances of any kind
23
+ * Trolling, insulting or derogatory comments, and personal or political attacks
24
+ * Public or private harassment
25
+ * Publishing others' private information, such as a physical or email
26
+ address, without their explicit permission
27
+ * Other conduct which could reasonably be considered inappropriate in a
28
+ professional setting
29
+
30
+ ## Enforcement Responsibilities
31
+
32
+ Community leaders are responsible for clarifying and enforcing our standards of acceptable behavior and will take appropriate and fair corrective action in response to any behavior that they deem inappropriate, threatening, offensive, or harmful.
33
+
34
+ Community leaders have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, and will communicate reasons for moderation decisions when appropriate.
35
+
36
+ ## Scope
37
+
38
+ This Code of Conduct applies within all community spaces, and also applies when an individual is officially representing the community in public spaces. Examples of representing our community include using an official e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event.
39
+
40
+ ## Enforcement
41
+
42
+ Instances of abusive, harassing, or otherwise unacceptable behavior may be reported to the community leaders responsible for enforcement at TODO: Write your email address. All complaints will be reviewed and investigated promptly and fairly.
43
+
44
+ All community leaders are obligated to respect the privacy and security of the reporter of any incident.
45
+
46
+ ## Enforcement Guidelines
47
+
48
+ Community leaders will follow these Community Impact Guidelines in determining the consequences for any action they deem in violation of this Code of Conduct:
49
+
50
+ ### 1. Correction
51
+
52
+ **Community Impact**: Use of inappropriate language or other behavior deemed unprofessional or unwelcome in the community.
53
+
54
+ **Consequence**: A private, written warning from community leaders, providing clarity around the nature of the violation and an explanation of why the behavior was inappropriate. A public apology may be requested.
55
+
56
+ ### 2. Warning
57
+
58
+ **Community Impact**: A violation through a single incident or series of actions.
59
+
60
+ **Consequence**: A warning with consequences for continued behavior. No interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, for a specified period of time. This includes avoiding interactions in community spaces as well as external channels like social media. Violating these terms may lead to a temporary or permanent ban.
61
+
62
+ ### 3. Temporary Ban
63
+
64
+ **Community Impact**: A serious violation of community standards, including sustained inappropriate behavior.
65
+
66
+ **Consequence**: A temporary ban from any sort of interaction or public communication with the community for a specified period of time. No public or private interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, is allowed during this period. Violating these terms may lead to a permanent ban.
67
+
68
+ ### 4. Permanent Ban
69
+
70
+ **Community Impact**: Demonstrating a pattern of violation of community standards, including sustained inappropriate behavior, harassment of an individual, or aggression toward or disparagement of classes of individuals.
71
+
72
+ **Consequence**: A permanent ban from any sort of public interaction within the community.
73
+
74
+ ## Attribution
75
+
76
+ This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 2.0,
77
+ available at https://www.contributor-covenant.org/version/2/0/code_of_conduct.html.
78
+
79
+ Community Impact Guidelines were inspired by [Mozilla's code of conduct enforcement ladder](https://github.com/mozilla/diversity).
80
+
81
+ [homepage]: https://www.contributor-covenant.org
82
+
83
+ For answers to common questions about this code of conduct, see the FAQ at
84
+ https://www.contributor-covenant.org/faq. Translations are available at https://www.contributor-covenant.org/translations.
data/Gemfile ADDED
@@ -0,0 +1,9 @@
1
+ # frozen_string_literal: true
2
+
3
+ source "https://rubygems.org"
4
+
5
+ # Specify your gem's dependencies in simply_fsm.gemspec
6
+ gemspec
7
+
8
+ gem "rake", "~> 13.0"
9
+ gem "rubocop", "~> 1.21"
data/Gemfile.lock ADDED
@@ -0,0 +1,55 @@
1
+ PATH
2
+ remote: .
3
+ specs:
4
+ simply_fsm (0.1.0)
5
+
6
+ GEM
7
+ remote: https://rubygems.org/
8
+ specs:
9
+ ast (2.4.2)
10
+ diff-lcs (1.5.0)
11
+ parallel (1.21.0)
12
+ parser (3.1.1.0)
13
+ ast (~> 2.4.1)
14
+ rainbow (3.1.1)
15
+ rake (13.0.6)
16
+ regexp_parser (2.2.1)
17
+ rexml (3.2.5)
18
+ rspec (3.11.0)
19
+ rspec-core (~> 3.11.0)
20
+ rspec-expectations (~> 3.11.0)
21
+ rspec-mocks (~> 3.11.0)
22
+ rspec-core (3.11.0)
23
+ rspec-support (~> 3.11.0)
24
+ rspec-expectations (3.11.0)
25
+ diff-lcs (>= 1.2.0, < 2.0)
26
+ rspec-support (~> 3.11.0)
27
+ rspec-mocks (3.11.0)
28
+ diff-lcs (>= 1.2.0, < 2.0)
29
+ rspec-support (~> 3.11.0)
30
+ rspec-support (3.11.0)
31
+ rubocop (1.25.1)
32
+ parallel (~> 1.10)
33
+ parser (>= 3.1.0.0)
34
+ rainbow (>= 2.2.2, < 4.0)
35
+ regexp_parser (>= 1.8, < 3.0)
36
+ rexml
37
+ rubocop-ast (>= 1.15.1, < 2.0)
38
+ ruby-progressbar (~> 1.7)
39
+ unicode-display_width (>= 1.4.0, < 3.0)
40
+ rubocop-ast (1.15.2)
41
+ parser (>= 3.0.1.1)
42
+ ruby-progressbar (1.11.0)
43
+ unicode-display_width (2.1.0)
44
+
45
+ PLATFORMS
46
+ ruby
47
+
48
+ DEPENDENCIES
49
+ rake (~> 13.0)
50
+ rspec (~> 3.0)
51
+ rubocop (~> 1.21)
52
+ simply_fsm!
53
+
54
+ BUNDLED WITH
55
+ 2.1.4
data/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2022 Kumanan Yogaratnam
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
data/README.md ADDED
@@ -0,0 +1,195 @@
1
+ # SimplyFSM
2
+
3
+ `simply_fsm` is a bare-necessities finite state machine data-type for use with any Ruby class. I created `simply_fsm` because I wanted the minimal FSM data type that was easy to use and did everything I would expect from a core data type.
4
+
5
+ If you need storage/persistence/Rails/etc support, I recommend [AASM](https://github.com/aasm/aasm) whose API was an inspiration for this gem.
6
+
7
+ **Contents**
8
+ - [Installation](#installation)
9
+ - [Usage](#usage)
10
+ - [One state machine](#one-state-machine)
11
+ - [Multiple state machines](#multiple-state-machines)
12
+ - [Handle failed events](#handle-failed-events)
13
+ - [Guarding events](#guarding-events)
14
+ - [Development](#development)
15
+ - [Contributing](#contributing)
16
+ - [License](#license)
17
+ - [Code of Conduct](#code-of-conduct)
18
+
19
+ ## Installation
20
+
21
+ Add this line to your application's Gemfile:
22
+
23
+ ```ruby
24
+ gem 'simply_fsm'
25
+ ```
26
+
27
+ And then execute:
28
+
29
+ $ bundle install
30
+
31
+ Or install it yourself as:
32
+
33
+ $ gem install simply_fsm
34
+
35
+ ## Usage
36
+
37
+ ### One state machine
38
+
39
+ Here's a single-state example of a `Job` class (unashamedly based on [this `aasm` example](https://github.com/aasm/aasm#usage)).
40
+
41
+ ```ruby
42
+ class Job
43
+ include SimplyFSM
44
+
45
+ state_machine :status do
46
+ state :sleeping, initial: true
47
+ state :running
48
+ state :cleaning
49
+
50
+ event :run, transition: { from: :sleeping, to: :running } do
51
+ # executed when transition succeeds
52
+ end
53
+
54
+ event :clean, transition: { from: :running, to: :cleaning } do
55
+ # do the cleaning since transition succeeded
56
+ end
57
+
58
+ event :sleep, transition: { from: [:running, :cleaning], to: :sleeping }
59
+ end
60
+ end
61
+ ```
62
+
63
+ This provides the following public methods for the class.
64
+
65
+ ```ruby
66
+ job = Job.new
67
+ job.status # => :sleeping
68
+ job.sleeping? # => true
69
+ job.may_run? # => true
70
+ job.run # => true on success
71
+ job.running? # => true
72
+ job.sleeping? # => false
73
+ job.may_run? # => false
74
+ job.run # => false on failure
75
+ ```
76
+
77
+ ### Multiple state machines
78
+
79
+ A class can define as many state machines as needed as long as each has a unique name.
80
+
81
+ ```ruby
82
+ class Player
83
+ include SimplyFSM
84
+
85
+ state_machine :motion do
86
+ state :idling, initial: true
87
+ state :walking
88
+
89
+ event :idle, transition: { from: :any, to: :idling }
90
+ event :walk, transition: { from: :idling, to: :walking }
91
+ end
92
+
93
+ state_machine :action do
94
+ state :ready, initial: true
95
+ state :blocking
96
+
97
+ event :hold, transition: { from: :any, to: :ready }
98
+ event :block, transition: { from: :any, to: :blocking }
99
+ end
100
+ end
101
+ ```
102
+ This provides the following public methods for the class.
103
+
104
+ | Public method for | `motion` state machine | `action` state machine |
105
+ | --------------------------- | ------------------------ | ------------------------- |
106
+ | current state | `motion` | `action` |
107
+ | event methods | `idle`, `walk` | `hold`, `block` |
108
+ | event precondition checking | `may_idle?`, `may_walk?` | `may_hold?`, `may_block?` |
109
+ | state checking | `idling?`, `walking?` | `ready?`, `blocking?` |
110
+
111
+ ### Handle failed events
112
+
113
+ It's possible to specify an ebent failure handler via lambda or method name either for the entire state machine or for each event. If specified, the `fail` handler is called before an event returns `false`
114
+
115
+ ```ruby
116
+ class JobWithErrors
117
+ class Error < StandardError; end
118
+ class RunError < StandardError; end
119
+
120
+ include SimplyFSM
121
+
122
+ state_machine :activity, fail: :on_any_fail do
123
+ state :sleeping, initial: true
124
+ state :running
125
+ state :cleaning
126
+
127
+ event :sleep, transition: { from: %i[running cleaning], to: :sleeping }
128
+ event :clean, transition: { from: :running, to: :cleaning }
129
+ event :run,
130
+ fail: ->(_event) { raise RunError, "Cannot run" },
131
+ transition: { from: :sleeping, to: :running }
132
+ end
133
+
134
+ def on_any_fail(event_name)
135
+ raise Error, "Cannot do: #{event_name}"
136
+ end
137
+ end
138
+ ```
139
+
140
+ ### Guarding events
141
+
142
+ It's possible guard events against additional constraints by specifying a lambda for each event which is executed in the instance of the class with the state machine. In addition to checking the allowed `from` state, the `guard`, if specified, must return `true` for the transition to occur.
143
+
144
+ ```ruby
145
+ class AgilePlayer
146
+ class LeapError < StandardError; end
147
+
148
+ include SimplyFSM
149
+
150
+ state_machine :motion do
151
+ state :idling, initial: true
152
+ state :walking
153
+ state :running
154
+
155
+ event :idle, transition: { from: :any, to: :idling }
156
+ event :walk, transition: { from: :any, to: :walking }
157
+ event :run, transition: { from: :any, to: :running }
158
+ end
159
+
160
+ state_machine :action do
161
+ state :ready, initial: true
162
+ state :jumping
163
+ state :leaping
164
+
165
+ event :hold, transition: { from: :any, to: :ready }
166
+ event :jump,
167
+ guard: -> { !running? },
168
+ transition: { from: :ready, to: :jumping }
169
+ event :leap,
170
+ guard: -> { running? },
171
+ fail: ->(_event) { raise LeapError, "Cannot leap" },
172
+ transition: { from: :ready, to: :leaping }
173
+ end
174
+ end
175
+ ```
176
+
177
+ ## Development
178
+
179
+ After checking out the repo, run `bin/setup` to install dependencies. Then, run `rake spec` to run the tests. You can also run `bin/console` for an interactive prompt that will allow you to experiment.
180
+
181
+ To install this gem onto your local machine, run `bundle exec rake install`. To release a new version, update the version number in `version.rb`, and then run `bundle exec rake release`, which will create a git tag for the version, push git commits and the created tag, and push the `.gem` file to [rubygems.org](https://rubygems.org).
182
+
183
+ ## Contributing
184
+
185
+ Bug reports and sugestions are welcome. Otherwise, at this time, this project is closed for code changes and pull requests. I appreciate your understanding.
186
+
187
+ This project is intended to be a safe, welcoming space for collaboration, and contributors are expected to adhere to the [code of conduct](https://github.com/nogginly/simply_fsm/blob/main/CODE_OF_CONDUCT.md).
188
+
189
+ ## License
190
+
191
+ The gem is available as open source under the terms of the [MIT License](https://opensource.org/licenses/MIT).
192
+
193
+ ## Code of Conduct
194
+
195
+ Everyone interacting in the `simply_fsm` project's codebases, issue trackers, chat rooms and mailing lists is expected to follow the [code of conduct](https://github.com/nogginly/simply_fsm/blob/main/CODE_OF_CONDUCT.md).
data/Rakefile ADDED
@@ -0,0 +1,12 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "bundler/gem_tasks"
4
+ require "rspec/core/rake_task"
5
+
6
+ RSpec::Core::RakeTask.new(:spec)
7
+
8
+ require "rubocop/rake_task"
9
+
10
+ RuboCop::RakeTask.new
11
+
12
+ task default: %i[spec rubocop]
data/bin/console ADDED
@@ -0,0 +1,15 @@
1
+ #!/usr/bin/env ruby
2
+ # frozen_string_literal: true
3
+
4
+ require "bundler/setup"
5
+ require "simply_fsm"
6
+
7
+ # You can add fixtures and/or initialization code here to make experimenting
8
+ # with your gem easier. You can also use a different console, if you like.
9
+
10
+ # (If you use this, don't forget to add pry to your Gemfile!)
11
+ # require "pry"
12
+ # Pry.start
13
+
14
+ require "irb"
15
+ IRB.start(__FILE__)
data/bin/setup ADDED
@@ -0,0 +1,8 @@
1
+ #!/usr/bin/env bash
2
+ set -euo pipefail
3
+ IFS=$'\n\t'
4
+ set -vx
5
+
6
+ bundle install
7
+
8
+ # Do any other automated setup that you need to do here
data/lib/simply_fsm.rb ADDED
@@ -0,0 +1,134 @@
1
+ # frozen_string_literal: true
2
+
3
+ module SimplyFSM
4
+ VERSION = "0.1.0"
5
+
6
+ def self.included(base)
7
+ base.extend(ClassMethods)
8
+ end
9
+
10
+ module ClassMethods
11
+ def state_machine(name, opts = {}, &block)
12
+ fsm = StateMachine.new(name, self, fail: opts[:fail])
13
+ fsm.instance_eval(&block)
14
+ end
15
+ end
16
+
17
+ class StateMachine
18
+ attr_reader :initial_state, :states, :events, :name, :full_name
19
+
20
+ def initialize(name, owner_class, fail: nil)
21
+ @owner_class = owner_class
22
+ @name = name.to_sym
23
+ @full_name = "#{owner_class.name}/#{name}"
24
+ @states = []
25
+ @events = []
26
+ @initial_state = nil
27
+ @fail_handler = fail
28
+
29
+ setup_base_methods
30
+ end
31
+
32
+ def state(state_name, initial: false)
33
+ unless state_name.nil? || @states.include?(state_name)
34
+ status = state_name.to_sym
35
+ state_machine_name = @name
36
+ @states << status
37
+ @initial_state = status if initial
38
+
39
+ make_owner_method "#{state_name}?", lambda {
40
+ send(state_machine_name) == status
41
+ }
42
+ end
43
+ end
44
+
45
+ def event(event_name, transition:, guard: nil, fail: nil, &after)
46
+ if event_name && transition
47
+ @events << event_name
48
+ from = transition[:from]
49
+ to = transition[:to]
50
+ state_machine_name = @name
51
+ var_name = "@#{state_machine_name}"
52
+ may_event_name = "may_#{event_name}?"
53
+ fail = @fail_handler if fail.nil?
54
+
55
+ setup_may_event_method may_event_name, from, to, guard
56
+
57
+ #
58
+ # Setup the event method to attempt to make the state
59
+ # transition or report failure
60
+ make_owner_method event_name, lambda {
61
+ if send(may_event_name)
62
+ instance_variable_set(var_name, to)
63
+ instance_exec(&after) if after
64
+ return true
65
+ end
66
+ # unable to satisfy pre-conditions for the event
67
+ if fail
68
+ if fail.is_a?(String) || fail.is_a?(Symbol)
69
+ send(fail, event_name)
70
+ else
71
+ instance_exec(event_name, &fail)
72
+ end
73
+ end
74
+ false
75
+ }
76
+
77
+ end
78
+ end
79
+
80
+ private
81
+
82
+ def setup_may_event_method(may_event_name, from, _to, guard)
83
+ state_machine_name = @name
84
+ #
85
+ # Instead of one "may_event?" method that checks all variations
86
+ # every time it's called, here we check the event definition and
87
+ # define the most optimal lambda to ensure the check is as fast as
88
+ # possible
89
+ method_lambda = if from == :any && !guard
90
+ -> { true } # unguarded transition from any state
91
+ elsif from == :any
92
+ guard # guarded transition from any state
93
+ elsif !guard
94
+ if from.is_a?(Array)
95
+ lambda { # unguarded transition from choice of states
96
+ current = send(state_machine_name)
97
+ from.include?(current)
98
+ }
99
+ else
100
+ lambda { # unguarded transition from one state
101
+ current = send(state_machine_name)
102
+ from == current
103
+ }
104
+ end
105
+ elsif from.is_a?(Array)
106
+ lambda { # guarded transition from choice of states
107
+ current = send(state_machine_name)
108
+ from.include?(current) && instance_exec(&guard)
109
+ }
110
+ else
111
+ lambda { # guarded transition from one state
112
+ current = send(state_machine_name)
113
+ from == current && instance_exec(&guard)
114
+ }
115
+ end
116
+ make_owner_method may_event_name, method_lambda
117
+ end
118
+
119
+ def setup_base_methods
120
+ var_name = "@#{name}"
121
+ fsm = self
122
+ make_owner_method @name, lambda {
123
+ instance_variable_get(var_name) ||
124
+ fsm.initial_state
125
+ }
126
+ make_owner_method "#{@name}_states", -> { fsm.states }
127
+ make_owner_method "#{@name}_events", -> { fsm.events }
128
+ end
129
+
130
+ def make_owner_method(method_name, method_definition)
131
+ @owner_class.define_method(method_name, method_definition)
132
+ end
133
+ end
134
+ end
@@ -0,0 +1,30 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "lib/simply_fsm"
4
+
5
+ Gem::Specification.new do |spec|
6
+ spec.name = "simply_fsm"
7
+ spec.version = SimplyFSM::VERSION
8
+ spec.authors = ["nogginly"]
9
+ spec.email = ["nogginly@icloud.com"]
10
+
11
+ spec.summary = "Simple finite state mechine (FSM) data-type mixin for Ruby objects."
12
+ spec.description = "Use it to setup one or more FSMs in any Ruby object."
13
+ spec.homepage = "https://github.com/nogginly/simply_fsm"
14
+ spec.license = "MIT"
15
+ spec.required_ruby_version = ">= 2.7.0"
16
+ spec.date = Time.now
17
+
18
+ spec.metadata["homepage_uri"] = spec.homepage
19
+ spec.metadata["source_code_uri"] = spec.homepage
20
+ spec.metadata["changelog_uri"] = "https://github.com/nogginly/simply_fsm/CHANGELOG.md"
21
+
22
+ spec.files = `git ls-files`.split("\n")
23
+ spec.test_files = `git ls-files -- {test,spec,features}/*`.split("\n")
24
+ spec.require_paths = ["lib"]
25
+
26
+ # no deployment dependencies
27
+
28
+ # development
29
+ spec.add_development_dependency "rspec", "~> 3.0"
30
+ end
@@ -0,0 +1,17 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "simply_fsm"
4
+
5
+ RSpec.configure do |config|
6
+ # Enable flags like --only-failures and --next-failure
7
+ config.example_status_persistence_file_path = ".rspec_status"
8
+
9
+ # Disable RSpec exposing methods globally on `Module` and `main`
10
+ config.disable_monkey_patching!
11
+
12
+ config.expect_with :rspec do |c|
13
+ c.syntax = :expect
14
+ end
15
+ end
16
+
17
+ Dir["./spec/support/**/*.rb"].sort.each { |f| require f }
@@ -0,0 +1,43 @@
1
+ # frozen_string_literal: true
2
+
3
+ RSpec.shared_examples "state machine basics" do |state_machine, initial_state:, states:, events:|
4
+ describe "state machine for #{state_machine}" do
5
+ it "initially #{initial_state}" do
6
+ expect(subject.send(state_machine)).to eq initial_state
7
+ end
8
+
9
+ context "defines event methods" do
10
+ events.each do |event|
11
+ it event.to_s do
12
+ expect(subject.class.method_defined?(event)).to be true
13
+ end
14
+ end
15
+ end
16
+
17
+ context "defines info methods" do
18
+ it "#{state_machine}_states" do
19
+ expect(subject.send("#{state_machine}_states")).to eq states
20
+ end
21
+
22
+ it "#{state_machine}_events" do
23
+ expect(subject.send("#{state_machine}_events")).to eq events
24
+ end
25
+ end
26
+
27
+ context "defines state methods" do
28
+ states.each do |state|
29
+ it "#{state}?" do
30
+ expect(subject.class.method_defined?("#{state}?")).to be true
31
+ end
32
+ end
33
+ end
34
+
35
+ context "defines event pre-condition methods" do
36
+ events.each do |event|
37
+ it "may_#{event}?" do
38
+ expect(subject.class.method_defined?("may_#{event}?")).to be true
39
+ end
40
+ end
41
+ end
42
+ end
43
+ end
@@ -0,0 +1,57 @@
1
+ # frozen_string_literal: true
2
+
3
+ class FailHandlingStateMachine
4
+ class Error < StandardError; end
5
+ class RunError < StandardError; end
6
+
7
+ include SimplyFSM
8
+
9
+ state_machine :activity, fail: :on_any_fail do
10
+ state :sleeping, initial: true
11
+ state :running
12
+ state :cleaning
13
+
14
+ event :sleep, transition: { from: %i[running cleaning], to: :sleeping }
15
+ event :clean, transition: { from: :running, to: :cleaning }
16
+ event :run,
17
+ fail: ->(_event) { raise RunError, "Cannot run" },
18
+ transition: { from: :sleeping, to: :running }
19
+ end
20
+
21
+ def on_any_fail(event_name)
22
+ raise Error, "Cannot do: #{event_name}"
23
+ end
24
+ end
25
+
26
+ RSpec.describe FailHandlingStateMachine do
27
+ describe "#sleep" do
28
+ it "error if already sleeping" do
29
+ expect { subject.sleep }.to raise_error(FailHandlingStateMachine::Error)
30
+ end
31
+ end
32
+
33
+ describe "#run" do
34
+ it "custom error if already running" do
35
+ subject.run
36
+ expect { subject.run }.to raise_error(FailHandlingStateMachine::RunError)
37
+ end
38
+
39
+ it "custom error if cleaning" do
40
+ subject.run
41
+ subject.clean
42
+ expect { subject.run }.to raise_error(FailHandlingStateMachine::RunError)
43
+ end
44
+ end
45
+
46
+ describe "#clean" do
47
+ it "error if sleeping" do
48
+ expect { subject.clean }.to raise_error(FailHandlingStateMachine::Error)
49
+ end
50
+
51
+ it "error if already cleaning" do
52
+ subject.run
53
+ subject.clean
54
+ expect { subject.clean }.to raise_error(FailHandlingStateMachine::Error)
55
+ end
56
+ end
57
+ end
@@ -0,0 +1,50 @@
1
+ # frozen_string_literal: true
2
+
3
+ class GuardingEvents
4
+ class LeapError < StandardError; end
5
+
6
+ include SimplyFSM
7
+
8
+ state_machine :motion do
9
+ state :idling, initial: true
10
+ state :walking
11
+ state :running
12
+
13
+ event :idle, transition: { from: :any, to: :idling }
14
+ event :walk, transition: { from: :any, to: :walking }
15
+ event :run, transition: { from: :any, to: :running }
16
+ end
17
+
18
+ state_machine :action do
19
+ state :ready, initial: true
20
+ state :jumping
21
+ state :leaping
22
+
23
+ event :hold, transition: { from: :any, to: :ready }
24
+ event :jump,
25
+ guard: -> { !running? },
26
+ transition: { from: :ready, to: :jumping }
27
+ event :leap,
28
+ guard: -> { running? },
29
+ fail: ->(_event) { raise LeapError, "Cannot leap" },
30
+ transition: { from: :ready, to: :leaping }
31
+ end
32
+ end
33
+
34
+ RSpec.describe GuardingEvents do
35
+ describe "#jump" do
36
+ it "guard fails if motion is running" do
37
+ subject.run
38
+ expect(subject.may_jump?).to be false
39
+ expect(subject.jump).to be false
40
+ end
41
+ end
42
+
43
+ describe "#leap" do
44
+ it "guard raises error if motion is not running" do
45
+ subject.walk
46
+ expect(subject.may_leap?).to be false
47
+ expect { subject.leap }.to raise_error(GuardingEvents::LeapError)
48
+ end
49
+ end
50
+ end
@@ -0,0 +1,80 @@
1
+ # frozen_string_literal: true
2
+
3
+ class OneStateMachine
4
+ include SimplyFSM
5
+
6
+ state_machine :activity do
7
+ state :sleeping, initial: true
8
+ state :running
9
+ state :cleaning
10
+
11
+ event :run, transition: { from: :sleeping, to: :running }
12
+ event :clean, transition: { from: :running, to: :cleaning }
13
+ event :sleep, transition: { from: %i[running cleaning], to: :sleeping }
14
+ end
15
+ end
16
+
17
+ RSpec.describe OneStateMachine do
18
+ include_examples "state machine basics", :activity,
19
+ initial_state: :sleeping,
20
+ states: %i[sleeping running cleaning],
21
+ events: %i[run clean sleep]
22
+
23
+ describe "#sleep" do
24
+ it "fails if already sleeping" do
25
+ expect(subject.may_sleep?).to be false
26
+ expect(subject.sleep).to be false
27
+ end
28
+ it "succeeds if running" do
29
+ subject.run
30
+ expect(subject.may_sleep?).to be true
31
+ expect(subject.sleep).to be true
32
+ end
33
+ it "succeeds if cleaning" do
34
+ subject.run
35
+ subject.clean
36
+ expect(subject.may_sleep?).to be true
37
+ expect(subject.sleep).to be true
38
+ end
39
+ end
40
+
41
+ describe "#run" do
42
+ it "succeeds if sleeping" do
43
+ expect(subject.may_run?).to be true
44
+ expect(subject.run).to be true
45
+ end
46
+
47
+ it "fails if already running" do
48
+ subject.run
49
+ expect(subject.may_run?).to be false
50
+ expect(subject.run).to be false
51
+ end
52
+
53
+ it "fails if cleaning" do
54
+ subject.run
55
+ subject.clean
56
+ expect(subject.may_run?).to be false
57
+ expect(subject.run).to be false
58
+ end
59
+ end
60
+
61
+ describe "#clean" do
62
+ it "succeeds if running" do
63
+ subject.run
64
+ expect(subject.may_clean?).to be true
65
+ expect(subject.clean).to be true
66
+ end
67
+
68
+ it "fails if sleeping" do
69
+ expect(subject.may_clean?).to be false
70
+ expect(subject.clean).to be false
71
+ end
72
+
73
+ it "fails if already cleaning" do
74
+ subject.run
75
+ subject.clean
76
+ expect(subject.may_clean?).to be false
77
+ expect(subject.clean).to be false
78
+ end
79
+ end
80
+ end
@@ -0,0 +1,17 @@
1
+ # frozen_string_literal: true
2
+
3
+ class UsingFSM
4
+ include SimplyFSM
5
+ end
6
+
7
+ RSpec.describe SimplyFSM do
8
+ it "has a version number" do
9
+ expect(SimplyFSM::VERSION).not_to be nil
10
+ end
11
+
12
+ describe "when included" do
13
+ it "sets up state machine constructor" do
14
+ expect(UsingFSM.respond_to?(:state_machine)).not_to be nil
15
+ end
16
+ end
17
+ end
@@ -0,0 +1,33 @@
1
+ # frozen_string_literal: true
2
+
3
+ class TwoStateMachines
4
+ include SimplyFSM
5
+
6
+ state_machine :motion do
7
+ state :idling, initial: true
8
+ state :walking
9
+
10
+ event :idle, transition: { from: :any, to: :idling }
11
+ event :walk, transition: { from: :idling, to: :walking }
12
+ end
13
+
14
+ state_machine :action do
15
+ state :ready, initial: true
16
+ state :blocking
17
+
18
+ event :hold, transition: { from: :any, to: :ready }
19
+ event :block, transition: { from: :any, to: :blocking }
20
+ end
21
+ end
22
+
23
+ RSpec.describe TwoStateMachines do
24
+ include_examples "state machine basics", :motion,
25
+ initial_state: :idling,
26
+ states: %i[idling walking],
27
+ events: %i[idle walk]
28
+
29
+ include_examples "state machine basics", :action,
30
+ initial_state: :ready,
31
+ states: %i[ready blocking],
32
+ events: %i[hold block]
33
+ end
metadata ADDED
@@ -0,0 +1,89 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: simply_fsm
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.0
5
+ platform: ruby
6
+ authors:
7
+ - nogginly
8
+ autorequire:
9
+ bindir: bin
10
+ cert_chain: []
11
+ date: 2022-02-21 00:00:00.000000000 Z
12
+ dependencies:
13
+ - !ruby/object:Gem::Dependency
14
+ name: rspec
15
+ requirement: !ruby/object:Gem::Requirement
16
+ requirements:
17
+ - - "~>"
18
+ - !ruby/object:Gem::Version
19
+ version: '3.0'
20
+ type: :development
21
+ prerelease: false
22
+ version_requirements: !ruby/object:Gem::Requirement
23
+ requirements:
24
+ - - "~>"
25
+ - !ruby/object:Gem::Version
26
+ version: '3.0'
27
+ description: Use it to setup one or more FSMs in any Ruby object.
28
+ email:
29
+ - nogginly@icloud.com
30
+ executables: []
31
+ extensions: []
32
+ extra_rdoc_files: []
33
+ files:
34
+ - ".gitignore"
35
+ - ".rspec"
36
+ - ".rubocop.yml"
37
+ - ".ruby-version"
38
+ - CHANGELOG.md
39
+ - CODE_OF_CONDUCT.md
40
+ - Gemfile
41
+ - Gemfile.lock
42
+ - LICENSE
43
+ - README.md
44
+ - Rakefile
45
+ - bin/console
46
+ - bin/setup
47
+ - lib/simply_fsm.rb
48
+ - simply_fsm.gemspec
49
+ - spec/spec_helper.rb
50
+ - spec/support/state_machine_examples.rb
51
+ - spec/unit/fail_events_spec.rb
52
+ - spec/unit/guard_events_spec.rb
53
+ - spec/unit/one_state_machine_spec.rb
54
+ - spec/unit/simply_fsm_spec.rb
55
+ - spec/unit/two_state_machines_spec.rb
56
+ homepage: https://github.com/nogginly/simply_fsm
57
+ licenses:
58
+ - MIT
59
+ metadata:
60
+ homepage_uri: https://github.com/nogginly/simply_fsm
61
+ source_code_uri: https://github.com/nogginly/simply_fsm
62
+ changelog_uri: https://github.com/nogginly/simply_fsm/CHANGELOG.md
63
+ post_install_message:
64
+ rdoc_options: []
65
+ require_paths:
66
+ - lib
67
+ required_ruby_version: !ruby/object:Gem::Requirement
68
+ requirements:
69
+ - - ">="
70
+ - !ruby/object:Gem::Version
71
+ version: 2.7.0
72
+ required_rubygems_version: !ruby/object:Gem::Requirement
73
+ requirements:
74
+ - - ">="
75
+ - !ruby/object:Gem::Version
76
+ version: '0'
77
+ requirements: []
78
+ rubygems_version: 3.1.6
79
+ signing_key:
80
+ specification_version: 4
81
+ summary: Simple finite state mechine (FSM) data-type mixin for Ruby objects.
82
+ test_files:
83
+ - spec/spec_helper.rb
84
+ - spec/support/state_machine_examples.rb
85
+ - spec/unit/fail_events_spec.rb
86
+ - spec/unit/guard_events_spec.rb
87
+ - spec/unit/one_state_machine_spec.rb
88
+ - spec/unit/simply_fsm_spec.rb
89
+ - spec/unit/two_state_machines_spec.rb