machiner 0.1.0

Sign up to get free protection for your applications and to get access to all the features.
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: eb268bd0623e86beb5efd5133ce3b402cb7ace81e79851737c0c01567456a80a
4
+ data.tar.gz: da8a20d4353123fcb572f7445a3182f26283f445bd02686a18a5615fb35e53a0
5
+ SHA512:
6
+ metadata.gz: 6c6bbd9236dcdff0634fe7c42f94a02f2e6275f240bdd1048408b7fbe27f7ad25fe016193c9a8cdcc1a114d3ac88526ce152e33fa2f65ff2c910833e15a94e94
7
+ data.tar.gz: 2456d646ef89e763325c09bb68f956430cbf1f10be8af0717bd4c133cd22a7eb61e526c63c35a6738b5456d710cb1de22aa14cb6fb0a329a7514ad52a5cfe84d
@@ -0,0 +1,16 @@
1
+ name: Ruby
2
+
3
+ on: [push,pull_request]
4
+
5
+ jobs:
6
+ build:
7
+ runs-on: ubuntu-latest
8
+ steps:
9
+ - uses: actions/checkout@v2
10
+ - name: Set up Ruby
11
+ uses: ruby/setup-ruby@v1
12
+ with:
13
+ ruby-version: 3.0.1
14
+ bundler-cache: true
15
+ - name: Run the default task
16
+ run: bundle exec rake
data/.gitignore ADDED
@@ -0,0 +1,12 @@
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
12
+ .byebug_history
data/.rspec ADDED
@@ -0,0 +1,3 @@
1
+ --format documentation
2
+ --color
3
+ --require spec_helper
data/.rubocop.yml ADDED
@@ -0,0 +1,32 @@
1
+ require:
2
+ - rubocop-rspec
3
+
4
+ AllCops:
5
+ TargetRubyVersion: 2.6
6
+
7
+ Style/StringLiterals:
8
+ Enabled: true
9
+ EnforcedStyle: double_quotes
10
+
11
+ Style/StringLiteralsInInterpolation:
12
+ Enabled: true
13
+ EnforcedStyle: double_quotes
14
+
15
+ Layout/LineLength:
16
+ Max: 120
17
+
18
+ Metrics/BlockLength:
19
+ Exclude:
20
+ - 'spec/**/*'
21
+
22
+ RSpec/MultipleMemoizedHelpers:
23
+ Max: 9
24
+
25
+ RSpec/ExampleLength:
26
+ Max: 10
27
+
28
+ Style/Semicolon:
29
+ Enabled: false
30
+
31
+ Style/Documentation:
32
+ Enabled: false
data/CHANGELOG.md ADDED
@@ -0,0 +1,3 @@
1
+ ## [0.1.0] - 2021-07-12
2
+
3
+ - Initial release
@@ -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 bombazook@gmail.com. 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,18 @@
1
+ # frozen_string_literal: true
2
+
3
+ source "https://rubygems.org"
4
+
5
+ # Specify your gem's dependencies in machiner.gemspec
6
+ gemspec
7
+
8
+ gem "rake", "~> 13.0"
9
+
10
+ gem "rspec", "~> 3.0"
11
+
12
+ gem "rubocop", "~> 1.7"
13
+
14
+ gem "rubocop-rspec"
15
+
16
+ gem "byebug"
17
+
18
+ gem "pry"
data/Gemfile.lock ADDED
@@ -0,0 +1,68 @@
1
+ PATH
2
+ remote: .
3
+ specs:
4
+ machiner (0.1.0)
5
+
6
+ GEM
7
+ remote: https://rubygems.org/
8
+ specs:
9
+ ast (2.4.2)
10
+ byebug (11.1.3)
11
+ coderay (1.1.3)
12
+ diff-lcs (1.4.4)
13
+ method_source (1.0.0)
14
+ parallel (1.20.1)
15
+ parser (3.0.2.0)
16
+ ast (~> 2.4.1)
17
+ pry (0.14.1)
18
+ coderay (~> 1.1)
19
+ method_source (~> 1.0)
20
+ rainbow (3.0.0)
21
+ rake (13.0.6)
22
+ regexp_parser (2.1.1)
23
+ rexml (3.2.5)
24
+ rspec (3.10.0)
25
+ rspec-core (~> 3.10.0)
26
+ rspec-expectations (~> 3.10.0)
27
+ rspec-mocks (~> 3.10.0)
28
+ rspec-core (3.10.1)
29
+ rspec-support (~> 3.10.0)
30
+ rspec-expectations (3.10.1)
31
+ diff-lcs (>= 1.2.0, < 2.0)
32
+ rspec-support (~> 3.10.0)
33
+ rspec-mocks (3.10.2)
34
+ diff-lcs (>= 1.2.0, < 2.0)
35
+ rspec-support (~> 3.10.0)
36
+ rspec-support (3.10.2)
37
+ rubocop (1.18.3)
38
+ parallel (~> 1.10)
39
+ parser (>= 3.0.0.0)
40
+ rainbow (>= 2.2.2, < 4.0)
41
+ regexp_parser (>= 1.8, < 3.0)
42
+ rexml
43
+ rubocop-ast (>= 1.7.0, < 2.0)
44
+ ruby-progressbar (~> 1.7)
45
+ unicode-display_width (>= 1.4.0, < 3.0)
46
+ rubocop-ast (1.8.0)
47
+ parser (>= 3.0.1.1)
48
+ rubocop-rspec (2.4.0)
49
+ rubocop (~> 1.0)
50
+ rubocop-ast (>= 1.1.0)
51
+ ruby-progressbar (1.11.0)
52
+ unicode-display_width (2.0.0)
53
+
54
+ PLATFORMS
55
+ arm64-darwin-20
56
+ x86_64-linux
57
+
58
+ DEPENDENCIES
59
+ byebug
60
+ machiner!
61
+ pry
62
+ rake (~> 13.0)
63
+ rspec (~> 3.0)
64
+ rubocop (~> 1.7)
65
+ rubocop-rspec
66
+
67
+ BUNDLED WITH
68
+ 2.2.23
data/LICENSE.txt ADDED
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2021 Alexander Kostrov
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
13
+ all 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
21
+ THE SOFTWARE.
data/README.md ADDED
@@ -0,0 +1,23 @@
1
+ # Machiner
2
+
3
+ ## Usage
4
+
5
+ Read [Example](https://github.com/bombazook/machiner/blob/master/examples/boats.rb)
6
+
7
+ ## Development
8
+
9
+ 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.
10
+
11
+ 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).
12
+
13
+ ## Contributing
14
+
15
+ Bug reports and pull requests are welcome on GitHub at https://github.com/[USERNAME]/machiner. 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/[USERNAME]/machiner/blob/master/CODE_OF_CONDUCT.md).
16
+
17
+ ## License
18
+
19
+ The gem is available as open source under the terms of the [MIT License](https://opensource.org/licenses/MIT).
20
+
21
+ ## Code of Conduct
22
+
23
+ Everyone interacting in the Machiner project's codebases, issue trackers, chat rooms and mailing lists is expected to follow the [code of conduct](https://github.com/[USERNAME]/machiner/blob/master/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 "machiner"
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/examples/boats.rb ADDED
@@ -0,0 +1,237 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "byebug"
4
+
5
+ module BoatStates
6
+ extend Machiner::States
7
+
8
+ meta key: :base
9
+
10
+ state :on_water, ->(b) { b[:docked] != true }
11
+ state :in_dock, ->(b) { b[:docked] == true }
12
+ state :stays, ->(b) { !b[:state] || b[:state] == "stays" }
13
+ state :ready_for_dock, ->(b, m) { m.state?(:on_water, b) }
14
+ end
15
+
16
+ module BoatTransitions
17
+ extend Machiner::Transitions
18
+
19
+ meta key: :base
20
+
21
+ transition :dock, ready_for_dock: :in_dock do |b|
22
+ b[:docked] = true
23
+ b.delete(:state)
24
+ b
25
+ end
26
+
27
+ transition :undock, in_dock: :on_water do |b|
28
+ b[:docked] = false
29
+ b
30
+ end
31
+ end
32
+
33
+ module PaddleboatStates
34
+ include BoatStates
35
+
36
+ meta key: :paddleboat
37
+
38
+ state :ready, ->(b, m) { !m.state?(:docked, b) && m.state?(:stays, b) && m.state?(:paddles_ready, b) }
39
+ state :paddles, ->(b) { b[:state] == "paddles" }
40
+ state :soft_paddles, ->(b) { !b[:paddles] || b[:paddles] == "soft" }
41
+ state :paddles_ready, ->(b) { b[:paddles] == "on water" }
42
+ state :ready_for_dock, ->(b, m) { m.state?(:on_water, b) && m.state?(:soft_paddles, b) }
43
+ end
44
+
45
+ module PaddleboatTransitions
46
+ include BoatTransitions
47
+
48
+ meta key: :paddleboat
49
+
50
+ transition :go, ready: :paddles do |b|
51
+ b[:state] = "paddles"
52
+ b
53
+ end
54
+
55
+ transition :stop, paddles: :stays do |b|
56
+ b[:state] = "stays"
57
+ b
58
+ end
59
+
60
+ transition :setup_paddles, soft_paddles: :paddles_ready do |b|
61
+ b[:paddles] = "on water"
62
+ b
63
+ end
64
+
65
+ transition :paddles_up, paddles_ready: :soft_paddles do |b|
66
+ b[:paddles] = "soft"
67
+ b
68
+ end
69
+
70
+ transition :dock, ready_for_dock: :docked do |b, m|
71
+ b = m.call(:dock, b, key: :base)
72
+ b.delete(:paddles)
73
+ b
74
+ end
75
+ end
76
+
77
+ module SailboatStates
78
+ include BoatStates
79
+
80
+ meta key: :sailboat
81
+
82
+ state :ready, ->(b, m) { !m.state?(:docked, b) && m.state?(:stays, b) && m.state?(:sail_ready, b) }
83
+ state :sail_down, ->(b) { !b[:sail] || b[:sail] == "down" }
84
+ state :sail_ready, ->(b) { b[:sail] == "ready" }
85
+ state :sails, ->(b) { b[:state] == "sails" }
86
+ state :ready_for_dock, ->(b, m) { m.state?(:on_water, b) && m.state?(:sail_down, b) }
87
+ end
88
+
89
+ module SailboatTransitions
90
+ include BoatTransitions
91
+
92
+ meta key: :sailboat
93
+
94
+ transition :go, ready: :sails do |b|
95
+ b[:state] = "sails"
96
+ b
97
+ end
98
+
99
+ transition :stop, sails: :stays do |b|
100
+ b[:state] = "stays"
101
+ b
102
+ end
103
+
104
+ transition :set_sail, sail_down: :sail_ready do |b|
105
+ b[:sail] = "ready"
106
+ b
107
+ end
108
+
109
+ transition :take_away_sail, sail_ready: :sail_down do |b|
110
+ b[:sail] = "down"
111
+ b
112
+ end
113
+
114
+ transition :dock, ready_for_dock: :docked do |b, m|
115
+ b = m.call(:dock, b, key: :base)
116
+ b.delete(:sail)
117
+ b
118
+ end
119
+ end
120
+
121
+ class PaddleboatMachine
122
+ include PaddleboatStates
123
+ include PaddleboatTransitions
124
+ end
125
+
126
+ puts "paddleboat cruise"
127
+ boat = { name: "Paddleboat 1", docked: true }
128
+ puts boat
129
+ machine = PaddleboatMachine.new
130
+ begin
131
+ machine.call(:go, boat)
132
+ rescue Machiner::WrongStateError
133
+ puts "Can't go in docked state"
134
+ end
135
+ machine.safe_call(:go, boat) # => another try with no effect but no exceptions
136
+ boat = machine.call(:undock, boat)
137
+ puts boat # => {name: "Paddleboat 1", docked: false}
138
+ boat = machine.call(:setup_paddles, boat)
139
+ puts boat # => {name: "Paddleboat 1", docked: false, paddles: 'on water'}
140
+ boat = machine.call(:go, boat)
141
+ puts boat # => {name: "Paddleboat 1", docked: false, paddles: 'on water', state: 'paddles'}
142
+ boat = machine.call(:stop, boat)
143
+ puts boat # => {name: "Paddleboat 1", docked: false, paddles: 'on water', state: 'stays'}
144
+
145
+ begin
146
+ machine.call(:dock, boat)
147
+ rescue Machiner::WrongStateError
148
+ puts "Can't dock with paddles on water"
149
+ end
150
+ boat = machine.call(:paddles_up, boat)
151
+ puts boat # => {name: "Paddleboat 1", docked: false, paddles: 'soft', state: 'stays'}
152
+ boat = machine.call(:dock, boat)
153
+ puts boat # => {name: "Paddleboat 1", docked: true}
154
+ puts "\n"
155
+
156
+ class SailboatMachine
157
+ include SailboatStates
158
+ include SailboatTransitions
159
+ end
160
+
161
+ # sailboat cruise is almost the same
162
+
163
+ class GalleyMachine
164
+ include PaddleboatStates
165
+ include SailboatStates
166
+ include PaddleboatTransitions
167
+ include SailboatTransitions
168
+
169
+ state :ready do |g, m|
170
+ ((m.state?(:soft_paddles, g) && m.state?(:sail_ready, g)) ||
171
+ (m.state?(:paddles_ready, g) && m.state?(:sail_down, g))) &&
172
+ (m.state?(:ready, g, key: :paddleboat) || m.state?(:ready, g, key: :sailboat))
173
+ end
174
+
175
+ state :ready_for_dock do |g, m|
176
+ m.state?(:ready_for_dock, g, key: :paddleboat) &&
177
+ m.state?(:ready_for_dock, g, key: :sailboat)
178
+ end
179
+
180
+ state :switchable do |g, m|
181
+ m.state?(:stays, g) && m.state?(:on_water, g) && (m.state?(:paddles_ready, g) || m.state?(:sail_ready, g))
182
+ end
183
+
184
+ transition :switch_engine, %i[switchable paddles_ready] => :sail_ready do |g, m|
185
+ g = m.call(:paddles_up, g)
186
+ m.call(:set_sail, g)
187
+ end
188
+
189
+ transition :switch_engine, %i[switchable sail_ready] => :paddles_ready do |g, m|
190
+ g = m.call(:take_away_sail, g)
191
+ m.call(:setup_paddles, g)
192
+ end
193
+
194
+ transition :dock, ready_for_dock: :docked do |g, m|
195
+ g = m.call(:dock, g, key: :base)
196
+ g.delete(:paddles)
197
+ g.delete(:sail)
198
+ g
199
+ end
200
+ end
201
+
202
+ # galley journey
203
+ puts "galley journey"
204
+ galley = { name: "Famous galley", docked: true }
205
+ puts galley
206
+ machine = GalleyMachine.new
207
+
208
+ galley = machine.call(:undock, galley)
209
+ puts galley # => {name: "Famous galley", docked: false}
210
+ # no wind, go on paddles
211
+ galley = machine.call(:setup_paddles, galley)
212
+ puts galley # => {name: "Famous galley", docked: false, paddles: "on water"}
213
+ galley = machine.call(:go, galley)
214
+ puts galley # => {name: "Famous galley", docked: false, paddles: "on water", state: "paddles"}
215
+ # it is windy now, lets change engine
216
+ begin
217
+ machine.call(:switch_engine, galley)
218
+ rescue Machiner::WrongStateError
219
+ puts "Can't switch engine in motion"
220
+ end
221
+ galley = machine.call(:stop, galley)
222
+ puts galley # => {name: "Famous galley", docked: false, paddles: "on water", state: "stays"}
223
+ galley = machine.call(:switch_engine, galley)
224
+ puts galley # => {name: "Famous galley", docked: false, paddles: "soft", sail: "ready", state: "stays"}
225
+ galley = machine.call(:go, galley)
226
+ puts galley # => {name: "Famous galley", docked: false, paddles: "soft", sail: "ready", state: "sails"}
227
+ galley = machine.call(:stop, galley)
228
+ puts galley
229
+ begin
230
+ machine.call(:dock, galley)
231
+ rescue Machiner::WrongStateError
232
+ puts "Can't dock while sail is ready or paddles are on water"
233
+ end
234
+ galley = machine.call(:take_away_sail, galley)
235
+ puts galley
236
+ galley = machine.call(:dock, galley)
237
+ puts galley
data/lib/machiner.rb ADDED
@@ -0,0 +1,15 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "machiner/version"
4
+
5
+ module Machiner
6
+ class Error < StandardError; end
7
+
8
+ class WrongTransitionError < Error; end
9
+
10
+ class WrongStateError < Error; end
11
+
12
+ autoload :Container, "machiner/container"
13
+ autoload :States, "machiner/states"
14
+ autoload :Transitions, "machiner/transitions"
15
+ end
@@ -0,0 +1,55 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Machiner
4
+ class Container
5
+ attr_accessor :supercontainers
6
+
7
+ def initialize(supercontainer = nil)
8
+ @container = {}
9
+ @supercontainers = []
10
+ @supercontainers << supercontainer if supercontainer
11
+ end
12
+
13
+ def register(key, value = nil, **meta, &block)
14
+ @container[[key.to_s, meta]] = block || value
15
+ end
16
+
17
+ def [](key_name, **meta)
18
+ full_key = @container.keys.detect do |k|
19
+ check_key_name_and_meta(k, key_name, meta)
20
+ end
21
+ return @container[full_key] if full_key
22
+
23
+ @supercontainers.detect { |i| i[key_name, **meta] }&.send(:[], key_name, **meta)
24
+ end
25
+
26
+ def filtered_keys(key_name, **meta)
27
+ local_keys = @container.keys.select do |k|
28
+ check_key_name_and_meta(k, key_name, meta)
29
+ end
30
+ return local_keys unless local_keys.empty?
31
+
32
+ @supercontainers.flat_map { |i| i.filtered_keys(key_name, **meta) }
33
+ end
34
+
35
+ def keys
36
+ full_keys.map(&:first)
37
+ end
38
+
39
+ def full_keys
40
+ @container.keys + @supercontainers.flat_map(&:full_keys)
41
+ end
42
+
43
+ def get_by_full_key(key)
44
+ @container[key] || @supercontainers.detect { |i| i.get_by_full_key(key) }&.get_by_full_key(key)
45
+ end
46
+
47
+ private
48
+
49
+ def check_key_name_and_meta(key, key_name, meta)
50
+ key.first == key_name.to_s && meta.all? do |meta_key, value|
51
+ key.last && key.last[meta_key] == value
52
+ end
53
+ end
54
+ end
55
+ end
@@ -0,0 +1,73 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "forwardable"
4
+
5
+ module Machiner
6
+ module States
7
+ def self.extended(base)
8
+ base.extend SingletonMethods
9
+ base.include InstanceMethods
10
+ end
11
+
12
+ module SingletonMethods
13
+ def state_container
14
+ @state_container ||= Container.new
15
+ end
16
+
17
+ def meta(**meta_hash)
18
+ @meta = meta_hash || {}
19
+ end
20
+
21
+ def included(base)
22
+ super
23
+ base.extend SingletonMethods
24
+ end
25
+
26
+ def inherited(base)
27
+ super
28
+ base.extend SingletonMethods
29
+ end
30
+
31
+ def self.extended(base)
32
+ return unless base.ancestors.include?(InstanceMethods)
33
+
34
+ base_container = base.ancestors[1..].detect { |i| i.respond_to? :state_container }&.state_container
35
+ return unless base_container
36
+
37
+ return if base.state_container.supercontainers.include?(base_container)
38
+
39
+ base.state_container.supercontainers << base_container
40
+ end
41
+
42
+ def state(key, value = nil, **meta, &block)
43
+ meta = @meta.merge(meta) if @meta
44
+ state_container.register(key, value, **meta, &block)
45
+ end
46
+
47
+ def state_names
48
+ state_container.keys.uniq
49
+ end
50
+
51
+ def state?(state_name, *data, **meta)
52
+ callable = state_container[state_name, **meta]
53
+ return false unless callable
54
+
55
+ if callable && callable.arity > data.size
56
+ callable.call(*data.clone, self)
57
+ else
58
+ callable.call(*data.clone)
59
+ end
60
+ end
61
+
62
+ def states(data)
63
+ state_container.keys.select { |state| state_container[state].call(data) }
64
+ end
65
+ end
66
+
67
+ module InstanceMethods
68
+ extend Forwardable
69
+
70
+ def_delegators "self.class", :state?, :state_names, :states
71
+ end
72
+ end
73
+ end
@@ -0,0 +1,114 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "forwardable"
4
+
5
+ module Machiner
6
+ module Transitions
7
+ def self.extended(base)
8
+ base.extend SingletonMethods
9
+ base.include InstanceMethods
10
+ end
11
+
12
+ module SingletonMethods
13
+ def transition_container
14
+ @transition_container ||= Container.new
15
+ end
16
+
17
+ def meta(**meta_hash)
18
+ @meta = meta_hash || {}
19
+ end
20
+
21
+ def included(base)
22
+ super
23
+ base.extend SingletonMethods
24
+ end
25
+
26
+ def inherited(base)
27
+ super
28
+ base.extend SingletonMethods
29
+ end
30
+
31
+ def self.extended(base)
32
+ return unless base.ancestors.include?(InstanceMethods)
33
+
34
+ base_container = base.ancestors[1..].detect { |i| i.respond_to? :transition_container }&.transition_container
35
+ return unless base_container
36
+
37
+ return if base.transition_container.supercontainers.include?(base_container)
38
+
39
+ base.transition_container.supercontainers << base_container
40
+ end
41
+
42
+ def transition(event_name, path, meta = {}, &block)
43
+ meta = @meta.merge(meta) if @meta
44
+ from_state = path.keys.first
45
+ to_state = path.values.first
46
+ meta.merge!(from: from_state, to: to_state)
47
+ transition_container.register(event_name, **meta, &block)
48
+ end
49
+
50
+ def transition_names
51
+ transition_container.keys.uniq
52
+ end
53
+
54
+ def transition?(event_name, *data, **meta)
55
+ transition_keys = transition_container.filtered_keys(event_name, **meta)
56
+ transition_keys.any? do |key|
57
+ transition_key_check(key, *data)
58
+ end
59
+ end
60
+
61
+ def transitions(*data, **meta)
62
+ transition_container.full_keys.select { |key| transition_key_check(key, *data, **meta) }
63
+ end
64
+
65
+ def call(event_name, *data, **meta)
66
+ raise ArgumentError if data.empty?
67
+
68
+ transition_keys = transition_container.filtered_keys(event_name, **meta)
69
+ raise WrongTransitionError if transition_keys.empty?
70
+
71
+ transition_key = transition_keys.detect do |key|
72
+ transition_key_check(key, *data)
73
+ end
74
+ raise WrongStateError unless transition_key
75
+
76
+ call_transition_by_full_key(transition_key, *data)
77
+ end
78
+
79
+ def safe_call(event_name, *data, **meta)
80
+ transition_keys = transition_container.filtered_keys(event_name, **meta)
81
+ return (data.size == 1 ? data[0] : data) if transition_keys.empty?
82
+
83
+ transition_key = transition_keys.detect do |key|
84
+ transition_key_check(key, *data)
85
+ end
86
+ return (data.size == 1 ? data[0] : data) unless transition_key
87
+
88
+ call_transition_by_full_key(transition_key, *data)
89
+ end
90
+
91
+ private
92
+
93
+ def call_transition_by_full_key(transition_key, *data)
94
+ transition = transition_container.get_by_full_key(transition_key)
95
+ if transition.arity > data.size
96
+ transition.call(*data.map(&:clone), self)
97
+ else
98
+ transition.call(*data.map(&:clone))
99
+ end
100
+ end
101
+
102
+ def transition_key_check(key, *data)
103
+ meta = key.last.except(:from, :to)
104
+ [key.last[:from]].flatten.all? { |state| state?(state, *data, **meta) }
105
+ end
106
+ end
107
+
108
+ module InstanceMethods
109
+ extend Forwardable
110
+
111
+ def_delegators "self.class", :transition?, :transition_names, :transitions, :call, :safe_call
112
+ end
113
+ end
114
+ end
@@ -0,0 +1,5 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Machiner
4
+ VERSION = "0.1.0"
5
+ end
data/machiner.gemspec ADDED
@@ -0,0 +1,37 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "lib/machiner/version"
4
+
5
+ Gem::Specification.new do |spec|
6
+ spec.name = "machiner"
7
+ spec.version = Machiner::VERSION
8
+ spec.authors = ["Alexander Kostrov"]
9
+ spec.email = ["bombazook@gmail.com"]
10
+
11
+ spec.summary = "External state-machine gem"
12
+ spec.description = "State-machines, that has external description of states and transitions"
13
+ spec.homepage = "https://machiner.kostrov.net"
14
+ spec.license = "MIT"
15
+ spec.required_ruby_version = ">= 2.6.0"
16
+
17
+ spec.metadata["allowed_push_host"] = "https://rubygems.org"
18
+
19
+ spec.metadata["homepage_uri"] = spec.homepage
20
+ spec.metadata["source_code_uri"] = "https://github.com/bombazook/machiner"
21
+ spec.metadata["changelog_uri"] = "https://raw.github.com/bombazook/machiner/CHANGELOG.md"
22
+
23
+ # Specify which files should be added to the gem when it is released.
24
+ # The `git ls-files -z` loads the files in the RubyGem that have been added into git.
25
+ spec.files = Dir.chdir(File.expand_path(__dir__)) do
26
+ `git ls-files -z`.split("\x0").reject { |f| f.match(%r{\A(?:test|spec|features)/}) }
27
+ end
28
+ spec.bindir = "exe"
29
+ spec.executables = spec.files.grep(%r{\Aexe/}) { |f| File.basename(f) }
30
+ spec.require_paths = ["lib"]
31
+
32
+ # Uncomment to register a new dependency of your gem
33
+ # spec.add_dependency "example-gem", "~> 1.0"
34
+
35
+ # For more information and examples about making a new gem, checkout our
36
+ # guide at: https://bundler.io/guides/creating_gem.html
37
+ end
metadata ADDED
@@ -0,0 +1,67 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: machiner
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.0
5
+ platform: ruby
6
+ authors:
7
+ - Alexander Kostrov
8
+ autorequire:
9
+ bindir: exe
10
+ cert_chain: []
11
+ date: 2021-07-18 00:00:00.000000000 Z
12
+ dependencies: []
13
+ description: State-machines, that has external description of states and transitions
14
+ email:
15
+ - bombazook@gmail.com
16
+ executables: []
17
+ extensions: []
18
+ extra_rdoc_files: []
19
+ files:
20
+ - ".github/workflows/main.yml"
21
+ - ".gitignore"
22
+ - ".rspec"
23
+ - ".rubocop.yml"
24
+ - CHANGELOG.md
25
+ - CODE_OF_CONDUCT.md
26
+ - Gemfile
27
+ - Gemfile.lock
28
+ - LICENSE.txt
29
+ - README.md
30
+ - Rakefile
31
+ - bin/console
32
+ - bin/setup
33
+ - examples/boats.rb
34
+ - lib/machiner.rb
35
+ - lib/machiner/container.rb
36
+ - lib/machiner/states.rb
37
+ - lib/machiner/transitions.rb
38
+ - lib/machiner/version.rb
39
+ - machiner.gemspec
40
+ homepage: https://machiner.kostrov.net
41
+ licenses:
42
+ - MIT
43
+ metadata:
44
+ allowed_push_host: https://rubygems.org
45
+ homepage_uri: https://machiner.kostrov.net
46
+ source_code_uri: https://github.com/bombazook/machiner
47
+ changelog_uri: https://raw.github.com/bombazook/machiner/CHANGELOG.md
48
+ post_install_message:
49
+ rdoc_options: []
50
+ require_paths:
51
+ - lib
52
+ required_ruby_version: !ruby/object:Gem::Requirement
53
+ requirements:
54
+ - - ">="
55
+ - !ruby/object:Gem::Version
56
+ version: 2.6.0
57
+ required_rubygems_version: !ruby/object:Gem::Requirement
58
+ requirements:
59
+ - - ">="
60
+ - !ruby/object:Gem::Version
61
+ version: '0'
62
+ requirements: []
63
+ rubygems_version: 3.2.15
64
+ signing_key:
65
+ specification_version: 4
66
+ summary: External state-machine gem
67
+ test_files: []