enum_machine-contrib 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: 8e7266c9b63527eb71ba12e52d236c39dfb32f7efb2119a7171181b535030e9b
4
+ data.tar.gz: 1aff769ce18c3addf053e73bb7672727eda86ad3f4707dda11f45a0f50005900
5
+ SHA512:
6
+ metadata.gz: 8135da25b19be77b3266baaa828d1e4e97bcf2cf8df76ceaca72c0cc394288b707629e39d6242c92446b6c4ff6b33e6e4dd39f5ef05ad0d6b875f5f15d706877
7
+ data.tar.gz: 90c6af41a3aacfc09659647ce9af33114a58c09fd68b3560cb73c6fec35235ffe9c2c54f783674025db1a609e0675a0fd275b6631330d664f3fc4852ac0aab5b
data/.rspec ADDED
@@ -0,0 +1,3 @@
1
+ --format documentation
2
+ --color
3
+ --require spec_helper
data/.rubocop.yml ADDED
@@ -0,0 +1,22 @@
1
+ inherit_gem:
2
+ rubocop-gp:
3
+ - ./config/default.yml
4
+
5
+ AllCops:
6
+ TargetRubyVersion: 2.6
7
+
8
+ Rails/ApplicationRecord:
9
+ Enabled: false
10
+
11
+ Metrics/ParameterLists:
12
+ CountKeywordArgs: false
13
+
14
+ Style/Next:
15
+ Enabled: false
16
+
17
+ Style/ClassVars:
18
+ Enabled: false
19
+
20
+ Naming/FileName:
21
+ Exclude:
22
+ - lib/enum_machine-contrib.rb
data/CHANGELOG.md ADDED
@@ -0,0 +1,5 @@
1
+ ## [Unreleased]
2
+
3
+ ## [0.1.0] - 2023-02-28
4
+
5
+ - 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 xronos.i.am@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,12 @@
1
+ # frozen_string_literal: true
2
+
3
+ source 'https://rubygems.org'
4
+
5
+ gemspec
6
+
7
+ gem 'enum_machine', github: 'corp-gp/enum_machine'
8
+ gem 'priscilla', github: 'corp-gp/priscilla'
9
+ gem 'pry', '~> 0.12'
10
+ gem 'rake', '~> 13.0'
11
+ gem 'rspec', '~> 3.9'
12
+ gem 'rubocop-gp', github: 'corp-gp/rubocop-gp'
data/Gemfile.lock ADDED
@@ -0,0 +1,128 @@
1
+ GIT
2
+ remote: https://github.com/corp-gp/enum_machine.git
3
+ revision: 644d24ec2c54fe5da7369ef3e0f61c199aa94116
4
+ specs:
5
+ enum_machine (0.1.0)
6
+ activemodel
7
+ activerecord
8
+ activesupport
9
+
10
+ GIT
11
+ remote: https://github.com/corp-gp/priscilla.git
12
+ revision: 46ba7460df8209dfe80e344beed07dfe56648aaf
13
+ specs:
14
+ priscilla (1.0.3)
15
+ colorize (~> 0.7)
16
+ rumoji (~> 0.3)
17
+
18
+ GIT
19
+ remote: https://github.com/corp-gp/rubocop-gp.git
20
+ revision: 133f07ae119a34f51f5e54cf4c7947334153ada4
21
+ specs:
22
+ rubocop-gp (0.0.2)
23
+ rubocop
24
+ rubocop-performance
25
+ rubocop-rails
26
+ rubocop-rspec
27
+
28
+ PATH
29
+ remote: .
30
+ specs:
31
+ enum_machine-contrib (0.1.0)
32
+ activesupport
33
+ enum_machine
34
+ ruby-graphviz
35
+
36
+ GEM
37
+ remote: https://rubygems.org/
38
+ specs:
39
+ activemodel (7.0.4.2)
40
+ activesupport (= 7.0.4.2)
41
+ activerecord (7.0.4.2)
42
+ activemodel (= 7.0.4.2)
43
+ activesupport (= 7.0.4.2)
44
+ activesupport (7.0.4.2)
45
+ concurrent-ruby (~> 1.0, >= 1.0.2)
46
+ i18n (>= 1.6, < 2)
47
+ minitest (>= 5.1)
48
+ tzinfo (~> 2.0)
49
+ ast (2.4.2)
50
+ coderay (1.1.3)
51
+ colorize (0.8.1)
52
+ concurrent-ruby (1.2.2)
53
+ diff-lcs (1.5.0)
54
+ i18n (1.12.0)
55
+ concurrent-ruby (~> 1.0)
56
+ json (2.6.3)
57
+ method_source (1.0.0)
58
+ minitest (5.17.0)
59
+ parallel (1.22.1)
60
+ parser (3.2.1.0)
61
+ ast (~> 2.4.1)
62
+ pry (0.14.2)
63
+ coderay (~> 1.1)
64
+ method_source (~> 1.0)
65
+ rack (3.0.4.1)
66
+ rainbow (3.1.1)
67
+ rake (13.0.6)
68
+ regexp_parser (2.7.0)
69
+ rexml (3.2.5)
70
+ rspec (3.12.0)
71
+ rspec-core (~> 3.12.0)
72
+ rspec-expectations (~> 3.12.0)
73
+ rspec-mocks (~> 3.12.0)
74
+ rspec-core (3.12.1)
75
+ rspec-support (~> 3.12.0)
76
+ rspec-expectations (3.12.2)
77
+ diff-lcs (>= 1.2.0, < 2.0)
78
+ rspec-support (~> 3.12.0)
79
+ rspec-mocks (3.12.3)
80
+ diff-lcs (>= 1.2.0, < 2.0)
81
+ rspec-support (~> 3.12.0)
82
+ rspec-support (3.12.0)
83
+ rubocop (1.46.0)
84
+ json (~> 2.3)
85
+ parallel (~> 1.10)
86
+ parser (>= 3.2.0.0)
87
+ rainbow (>= 2.2.2, < 4.0)
88
+ regexp_parser (>= 1.8, < 3.0)
89
+ rexml (>= 3.2.5, < 4.0)
90
+ rubocop-ast (>= 1.26.0, < 2.0)
91
+ ruby-progressbar (~> 1.7)
92
+ unicode-display_width (>= 2.4.0, < 3.0)
93
+ rubocop-ast (1.27.0)
94
+ parser (>= 3.2.1.0)
95
+ rubocop-capybara (2.17.1)
96
+ rubocop (~> 1.41)
97
+ rubocop-performance (1.16.0)
98
+ rubocop (>= 1.7.0, < 2.0)
99
+ rubocop-ast (>= 0.4.0)
100
+ rubocop-rails (2.18.0)
101
+ activesupport (>= 4.2.0)
102
+ rack (>= 1.1)
103
+ rubocop (>= 1.33.0, < 2.0)
104
+ rubocop-rspec (2.18.1)
105
+ rubocop (~> 1.33)
106
+ rubocop-capybara (~> 2.17)
107
+ ruby-graphviz (1.2.5)
108
+ rexml
109
+ ruby-progressbar (1.11.0)
110
+ rumoji (0.5.0)
111
+ tzinfo (2.0.6)
112
+ concurrent-ruby (~> 1.0)
113
+ unicode-display_width (2.4.2)
114
+
115
+ PLATFORMS
116
+ x86_64-linux
117
+
118
+ DEPENDENCIES
119
+ enum_machine!
120
+ enum_machine-contrib!
121
+ priscilla!
122
+ pry (~> 0.12)
123
+ rake (~> 13.0)
124
+ rspec (~> 3.9)
125
+ rubocop-gp!
126
+
127
+ BUNDLED WITH
128
+ 2.4.6
data/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2023 corp-gp
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/LICENSE.txt ADDED
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2023 Sergei Malykh
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,79 @@
1
+ # EnumMachine extensions and tools
2
+
3
+ This repository contains extensions and development tools for the [enum_machine](https://github.com/corp-gp/enum_machine)
4
+
5
+ ## Installation
6
+
7
+ Install the gem and add to the application's Gemfile by executing:
8
+
9
+ $ bundle add enum_machine-contrib ruby-graphviz --group "development"
10
+
11
+ If bundler is not being used to manage dependencies, install the gem by executing:
12
+
13
+ $ gem install enum_machine-contrib ruby-graphviz
14
+
15
+ The gem depends on [GraphViz](https://graphviz.org/). See the [installation notes](https://graphviz.org/download/)
16
+
17
+ ## Usage
18
+
19
+ Suppose we have `Order` AR-model with the state machine specified by [enum_machine](https://github.com/corp-gp/enum_machine)
20
+
21
+ `config/initializers/enum_machine.rb`
22
+ ```ruby
23
+ require 'enum_machine_contrib/enum_machine'
24
+ ```
25
+
26
+ `app/models/order.rb`
27
+ ```ruby
28
+ class Order < ActiveRecord::Base
29
+ enum_machine :state, %w[s0 s1 s2 s3 s3.1 s3.2 s4 s4.1 s4.2 s5 s6 s6.1 s6.2 s7 s8 s9 s10 s11] do
30
+ transitions(
31
+ nil => %w[s0],
32
+ 's0' => %w[s1],
33
+ 's1' => %w[s2],
34
+ 's2' => %w[s3],
35
+ 's3' => %w[s3.1 s3.2 s4],
36
+ 's3.1' => %w[s1],
37
+ 's3.2' => %w[s1],
38
+ 's4' => %w[s4.1 s4.2 s5],
39
+ 's4.1' => %w[s2],
40
+ 's4.2' => %w[s2],
41
+ 's5' => %w[s6.1 s6.2],
42
+ 's6.2' => %w[s7],
43
+ 's6.1' => %w[s8],
44
+ 's8' => %w[s9],
45
+ 's9' => %w[s10],
46
+ 's7' => %w[s11],
47
+ 's10' => %w[s11],
48
+ )
49
+ end
50
+ end
51
+ ```
52
+
53
+ The gem allows you to get a visual representation of the graph of state transitions.
54
+
55
+ ```ruby
56
+ Order::STATE.machine.decision_tree.visualize.output(png: 'states.png')
57
+ ```
58
+
59
+ You will see:
60
+
61
+ ![states.png](states.png?raw=true "states")
62
+
63
+ ## Development
64
+
65
+ 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.
66
+
67
+ 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).
68
+
69
+ ## Contributing
70
+
71
+ Bug reports and pull requests are welcome on GitHub at https://github.com/[USERNAME]/enum_machine-contrib. 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]/enum_machine-contrib/blob/master/CODE_OF_CONDUCT.md).
72
+
73
+ ## License
74
+
75
+ The gem is available as open source under the terms of the [MIT License](https://opensource.org/licenses/MIT).
76
+
77
+ ## Code of Conduct
78
+
79
+ Everyone interacting in the EnumMachine::Contrib project's codebases, issue trackers, chat rooms and mailing lists is expected to follow the [code of conduct](https://github.com/[USERNAME]/enum_machine-contrib/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]
@@ -0,0 +1,41 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative 'lib/enum_machine_contrib/version'
4
+
5
+ Gem::Specification.new do |spec|
6
+ spec.name = 'enum_machine-contrib'
7
+ spec.version = EnumMachineContrib::VERSION
8
+ spec.authors = ['Sergei Malykh']
9
+ spec.email = ['xronos.i.am@gmail.com']
10
+
11
+ spec.summary = 'extensions and tools for enum_machine'
12
+ spec.homepage = 'https://github.com/corp-gp/enum_machine-contrib'
13
+ spec.license = 'MIT'
14
+ spec.required_ruby_version = '>= 2.6.0'
15
+
16
+ spec.metadata['allowed_push_host'] = 'https://rubygems.org'
17
+
18
+ spec.metadata['homepage_uri'] = spec.homepage
19
+ spec.metadata['source_code_uri'] = 'https://github.com/corp-gp/enum_machine-contrib'
20
+ spec.metadata['changelog_uri'] = 'https://github.com/corp-gp/enum_machine-contrib/CHANGELOG.md'
21
+
22
+ # Specify which files should be added to the gem when it is released.
23
+ # The `git ls-files -z` loads the files in the RubyGem that have been added into git.
24
+ spec.files =
25
+ Dir.chdir(__dir__) do
26
+ `git ls-files -z`.split("\x0").reject do |f|
27
+ (f == __FILE__) || f.match(%r{\A(?:(?:bin|test|spec|features)/|\.(?:git|circleci)|appveyor)})
28
+ end
29
+ end
30
+ spec.bindir = 'exe'
31
+ spec.executables = spec.files.grep(%r{\Aexe/}) { |f| File.basename(f) }
32
+ spec.require_paths = ['lib']
33
+
34
+ spec.add_dependency 'activesupport'
35
+ spec.add_dependency 'enum_machine'
36
+ spec.add_dependency 'ruby-graphviz'
37
+
38
+ # For more information and examples about making a new gem, check out our
39
+ # guide at: https://bundler.io/guides/creating_gem.html
40
+ spec.metadata['rubygems_mfa_required'] = 'true'
41
+ end
@@ -0,0 +1,3 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'enum_machine_contrib'
@@ -0,0 +1,205 @@
1
+ # frozen_string_literal: true
2
+
3
+ module EnumMachineContrib
4
+ class DecisionGraph
5
+
6
+ attr_accessor :vertexes, :edges
7
+
8
+ def initialize(graph)
9
+ @vertexes = Set.new
10
+ @edges = Set.new
11
+
12
+ vertex_by_value = {}
13
+ graph.each do |from_value, to_value_list|
14
+ from_value = array_wrap(from_value)
15
+ vertex_by_value[from_value] ||= Vertex[from_value]
16
+ from_vertex = vertex_by_value[from_value]
17
+ @vertexes << from_vertex
18
+
19
+ to_value_list.sort_by(&:to_s).each do |to_value|
20
+ to_value = array_wrap(to_value)
21
+ vertex_by_value[to_value] ||= Vertex[to_value]
22
+ to_vertex = vertex_by_value[to_value]
23
+ @vertexes << to_vertex
24
+
25
+ @edges << from_vertex.add_edge(to_vertex)
26
+ end
27
+ end
28
+ end
29
+
30
+ def decision_tree
31
+ drop_self_cycled_edges!
32
+ combine_equal_vertexes!
33
+
34
+ loop do
35
+ complexity_was = complexity
36
+
37
+ decision_tree = DecisionTree.wrap(to_h)
38
+ decision_tree.resolve!
39
+ resolved_decision_tree = decision_tree.resolved
40
+
41
+ edges.each do |edge|
42
+ next unless resolved_decision_tree.key?(edge.from.value)
43
+
44
+ if resolved_decision_tree[edge.from.value].any? { |to_value_list| to_value_list.include?(edge.to.value) }
45
+ edge.resolved!
46
+ end
47
+ end
48
+
49
+ strongly_connected_components = decision_tree.values.filter(&:cycled?)
50
+ strongly_connected_components.each do |strongly_connected_component|
51
+ resolve_strong_component!(strongly_connected_component)
52
+ end
53
+
54
+ break if complexity == complexity_was
55
+ end
56
+
57
+ decision_tree = DecisionTree[vertexes.index_by(&:value)]
58
+ decision_tree.resolve!
59
+ decision_tree
60
+ end
61
+
62
+ def to_h
63
+ vertexes.filter(&:active?).to_h do |vertex|
64
+ [
65
+ vertex.value,
66
+ vertex.outcoming_edges.filter_map { |edge| edge.to.value if edge.active? },
67
+ ]
68
+ end
69
+ end
70
+
71
+ private def complexity
72
+ edges.count(&:active?)
73
+ end
74
+
75
+ private def drop_self_cycled_edges!
76
+ edges.each do |edge|
77
+ edge.dropped! if edge.from == edge.to
78
+ end
79
+ end
80
+
81
+ private def combine_equal_vertexes!
82
+ vertexes.group_by { |vertex| [vertex.incoming_edges.map(&:from), vertex.outcoming_edges.map(&:to)] }.each_value do |combining_vertexes|
83
+ next if combining_vertexes.size < 2
84
+
85
+ new_vertex = Vertex.replace!(combining_vertexes)
86
+ new_vertex.combined!
87
+
88
+ @vertexes << new_vertex
89
+
90
+ @edges.merge(new_vertex.incoming_edges)
91
+ @edges.merge(new_vertex.outcoming_edges)
92
+ end
93
+ end
94
+
95
+ def resolve_strong_component!(component_cycled_vertex) # rubocop:disable Metrics/CyclomaticComplexity,Metrics/PerceivedComplexity
96
+ input_values = component_cycled_vertex.incoming_edges.filter(&:active?).flat_map { |edge| edge.from.value }
97
+ output_values = component_cycled_vertex.outcoming_edges.filter(&:active?).flat_map { |vertex| vertex.to.value }
98
+
99
+ active_vertexes = vertexes.filter(&:active?)
100
+ input_vertexes = active_vertexes.filter { |vertex| (input_values & vertex.value).any? }
101
+ output_vertexes = active_vertexes.filter { |vertex| (output_values & vertex.value).any? }
102
+
103
+ component_vertexes = active_vertexes.filter { |vertex| (component_cycled_vertex.value & vertex.value).any? }
104
+
105
+ single_incoming_vertexes = (component_vertexes + output_vertexes).filter { |vertex| vertex.incoming_edges.size == 1 }
106
+ single_incoming_vertexes.each do |to_vertex|
107
+ from_vertex = to_vertex.incoming_edges.first.from
108
+
109
+ (from_vertex.incoming_edges + from_vertex.outcoming_edges)
110
+ .group_by { |edge| [edge.from.value.to_s, edge.to.value.to_s].sort }
111
+ .values
112
+ .filter { |current_edges| current_edges.size > 1 }.each do |current_edges|
113
+ current_edges.each do |edge|
114
+ # S1 -> S2; S2 -> [S1, S3]
115
+ # drops back reference S2 -> S1
116
+ edge.dropped! if edge.from == from_vertex
117
+ end
118
+ end
119
+ end
120
+
121
+ resolved_not_visited_vertexes = []
122
+
123
+ current_vertexes = [component_cycled_vertex]
124
+ loop do
125
+ next_vertexes = current_vertexes.flat_map { |vertex| vertex.outcoming_edges.filter_map { |edge| edge.to if edge.active? } }
126
+ resolved_not_visited_vertexes += next_vertexes.reject(&:cycled?)
127
+ current_vertexes = next_vertexes
128
+ break if next_vertexes.empty?
129
+ end
130
+
131
+ single_incoming_chains = []
132
+ single_incoming_vertexes.each do |vertex|
133
+ single_incoming_edge = vertex.incoming_edges.first
134
+ # S1 -> [S2, S3]; S2 -> S3
135
+ # resolve S1 -> S2 because it is only one path to S2
136
+ single_incoming_edge.resolved!
137
+
138
+ resolved_not_visited_vertexes << single_incoming_edge.to
139
+
140
+ current_chain = single_incoming_chains.detect { |chain| chain.first == single_incoming_edge.to || chain.last == single_incoming_edge.from }
141
+ if current_chain
142
+ current_chain.replace(
143
+ if current_chain.first == single_incoming_edge.to
144
+ current_chain.unshift(single_incoming_edge.from)
145
+ else
146
+ current_chain.push(single_incoming_edge.to)
147
+ end,
148
+ )
149
+ else
150
+ single_incoming_chains << [single_incoming_edge.from, single_incoming_edge.to]
151
+ end
152
+ end
153
+
154
+ single_incoming_chains.each do |chain|
155
+ chain.flat_map { |vertex| vertex.outcoming_edges.to_a }.group_by(&:to).each_value do |outcoming_edges|
156
+ next if outcoming_edges.size < 2
157
+
158
+ # S1 -> [S2, S3]; S2 -> S3
159
+ # drops S1 -> S3, because S1 -> S2 resolved as only one path and S3 is reachable from S2
160
+ outcoming_edges[0..outcoming_edges.size - 2].each(&:dropped!)
161
+ end
162
+ end
163
+
164
+ current_vertexes = input_vertexes
165
+ visited_vertexes = []
166
+ loop do
167
+ current_following_vertexes = current_vertexes.flat_map { |vertex| vertex.outcoming_edges.map(&:to) }.uniq - visited_vertexes
168
+
169
+ if current_following_vertexes.size > 1
170
+ reachable_vertexes = resolved_not_visited_vertexes.flat_map { |vertex| vertex.outcoming_edges.map(&:to) }.uniq
171
+ break if reachable_vertexes.empty?
172
+
173
+ current_following_vertexes -= reachable_vertexes
174
+ end
175
+
176
+ current_vertexes.each do |from_vertex|
177
+ from_vertex.outcoming_edges.each do |edge|
178
+ next if edge.resolved?
179
+
180
+ if current_following_vertexes.include?(edge.to)
181
+ edge.resolved! if current_following_vertexes.size == 1
182
+ elsif resolved_not_visited_vertexes.include?(edge.to)
183
+ edge.dropped!
184
+ end
185
+ end
186
+ end
187
+
188
+ current_vertexes = current_following_vertexes
189
+ resolved_not_visited_vertexes -= current_following_vertexes
190
+ visited_vertexes += current_vertexes
191
+
192
+ break if current_vertexes.empty?
193
+ end
194
+ end
195
+
196
+ def array_wrap(value)
197
+ if value.nil?
198
+ [nil]
199
+ else
200
+ Array.wrap(value)
201
+ end
202
+ end
203
+
204
+ end
205
+ end
@@ -0,0 +1,168 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'tsort'
4
+
5
+ module EnumMachineContrib
6
+ class DecisionTree < Hash
7
+
8
+ include TSort
9
+
10
+ def tsort_each_child(node, &_block)
11
+ fetch(node).outcoming_edges.each { |edge| yield(edge.to.value) if edge.active? }
12
+ end
13
+
14
+ def tsort_each_node(&_block)
15
+ each_value { |vertex| yield(vertex.value) if vertex.active? }
16
+ end
17
+
18
+ def self.wrap(hsh)
19
+ vertex_by_value = {}
20
+
21
+ hsh.each do |from_value, to_value_list|
22
+ vertex_by_value[from_value] ||= Vertex[from_value]
23
+ from_vertex = vertex_by_value[from_value]
24
+
25
+ to_value_list.each do |to_value|
26
+ vertex_by_value[to_value] ||= Vertex[to_value]
27
+ from_vertex.add_edge(vertex_by_value[to_value])
28
+ end
29
+ end
30
+
31
+ DecisionTree[vertex_by_value]
32
+ end
33
+
34
+ def resolve!
35
+ strongly_connected_components.each do |strongly_connected_values|
36
+ next if strongly_connected_values.size < 2
37
+
38
+ clusterize_strong_component!(values_at(*strongly_connected_values))
39
+ end
40
+
41
+ values_topological_sorted = tsort.reverse
42
+ vertexes_topological_sorted = values_at(*values_topological_sorted)
43
+
44
+ start_vertex = vertexes_topological_sorted.shift
45
+ start_vertex.level = 0
46
+
47
+ visited_vertexes = [].unshift(start_vertex)
48
+
49
+ vertexes_topological_sorted.each do |to_vertex|
50
+ current_edge = nil
51
+
52
+ visited_vertexes.each do |vertex|
53
+ current_edge = fetch(vertex.value).outcoming_edges.detect { |edge| edge.to == to_vertex }
54
+ break if current_edge
55
+ end
56
+
57
+ to_vertex.level = current_edge.from.level + 1
58
+ current_edge.resolved!
59
+
60
+ visited_vertexes.unshift(to_vertex)
61
+ end
62
+
63
+ each_value do |vertex|
64
+ vertex.outcoming_edges.each do |edge|
65
+ edge.dropped! unless edge.resolved?
66
+ end
67
+ end
68
+ end
69
+
70
+ def resolved
71
+ resolved_hash = {}
72
+
73
+ each_value do |vertex|
74
+ next unless vertex.active?
75
+
76
+ resolved_hash[vertex.value] = vertex.outcoming_edges.filter_map { |edge| edge.to.value if edge.active? }
77
+ end
78
+
79
+ resolved_hash
80
+ end
81
+
82
+ ACTIVE_EDGE_STYLE = 'color=red penwidth=2'
83
+ INACTIVE_EDGE_STYLE = 'color=grey'
84
+
85
+ CLEAN_ID = proc { |s| s.gsub(/[^[[:alnum:]]]/, '_') }
86
+
87
+ def as_dot # rubocop:disable Metrics/CyclomaticComplexity,Metrics/PerceivedComplexity
88
+ combined_values = values.filter(&:combined?).flat_map(&:value).to_set
89
+ visible_vertexes = values.reject { |vertex| (combined_values & vertex.value).any? && !vertex.combined? }
90
+
91
+ cycled_vertexes, plain_vertexes = visible_vertexes.partition(&:cycled?)
92
+
93
+ nodes =
94
+ visible_vertexes
95
+ .map.with_index { |vertex, cluster_id|
96
+ [
97
+ vertex,
98
+ if vertex.value.compact.blank?
99
+ { id: 'null', label: 'nil' }
100
+ elsif vertex.combined?
101
+ { id: vertex.value.map(&CLEAN_ID).join('__'), label: vertex.value.join('/') }
102
+ elsif vertex.cycled?
103
+ { id: vertex.value[0].then(&CLEAN_ID), cluster_id: "cluster_#{cluster_id}" }
104
+ else
105
+ { id: vertex.value.join.then(&CLEAN_ID), label: vertex.value.join }
106
+ end,
107
+ ]
108
+ }
109
+ .to_h
110
+
111
+ vertexes_by_level = visible_vertexes.filter(&:level).sort_by(&:level).group_by(&:level)
112
+ node_ranks =
113
+ vertexes_by_level.map do |_level, vertexes_same_rank|
114
+ "{ rank=same #{vertexes_same_rank.reject(&:combined?).reject(&:cycled?).map { |vertex| nodes[vertex][:id] }.join(' ')} }"
115
+ end
116
+
117
+ node_labels = plain_vertexes.map { |vertex| "#{nodes[vertex][:id]} [label=\"#{nodes[vertex][:label]}\"]" }
118
+
119
+ clusters =
120
+ cycled_vertexes.map do |vertex|
121
+ "subgraph #{nodes[vertex][:cluster_id]} { color=blue style=dashed #{vertex.value.join(' ')} }"
122
+ end
123
+
124
+ transitions =
125
+ visible_vertexes.flat_map do |vertex|
126
+ vertex.outcoming_edges.filter_map do |edge|
127
+ if (!edge.from.combined? && (combined_values & edge.from.value).any?) ||
128
+ (!edge.to.combined? && (combined_values & edge.to.value).any?)
129
+ next
130
+ end
131
+
132
+ attrs = []
133
+ if edge.active?
134
+ attrs << ACTIVE_EDGE_STYLE
135
+ attrs << "ltail=#{nodes[edge.from][:cluster_id]}" if edge.from.cycled?
136
+ attrs << "lhead=#{nodes[edge.to][:cluster_id]}" if edge.to.cycled?
137
+ else
138
+ attrs << INACTIVE_EDGE_STYLE
139
+ end
140
+ "#{nodes[edge.from][:id]} -> #{nodes[edge.to][:id]} [#{attrs.join(' ')}]"
141
+ end
142
+ end
143
+
144
+ <<~DOT
145
+ digraph {
146
+ ranksep="1.0 equally"
147
+ compound=true
148
+ #{clusters.join("\n")}
149
+ #{node_labels.join('; ')}
150
+ #{node_ranks.join('; ')}
151
+ #{transitions.join("\n")}
152
+ }
153
+ DOT
154
+ end
155
+
156
+ def visualize
157
+ GraphViz.parse_string(as_dot)
158
+ end
159
+
160
+ private def clusterize_strong_component!(replacing_vertexes)
161
+ new_vertex = Vertex.replace!(replacing_vertexes)
162
+ new_vertex.cycled!
163
+
164
+ self[new_vertex.value] = new_vertex
165
+ end
166
+
167
+ end
168
+ end
@@ -0,0 +1,53 @@
1
+ # frozen_string_literal: true
2
+
3
+ module EnumMachineContrib
4
+
5
+ Edge =
6
+ Struct.new(:from, :to) do
7
+ attr_accessor :mode
8
+
9
+ EDGE_MODES = %i[pending resolved dropped].freeze # rubocop:disable Lint/ConstantDefinitionInBlock
10
+
11
+ def initialize(from, to)
12
+ self.from = from
13
+ self.to = to
14
+
15
+ pending!
16
+ end
17
+
18
+ EDGE_MODES.each do |mode|
19
+ class_eval <<-RUBY, __FILE__, __LINE__ + 1
20
+ # def resolved!
21
+ # self.mode = :resolved
22
+ # end
23
+ # def resolved?
24
+ # self.mode == :resolved
25
+ # end
26
+
27
+ def #{mode}!
28
+ self.mode = :#{mode}
29
+ end
30
+ def #{mode}?
31
+ self.mode == :#{mode}
32
+ end
33
+ RUBY
34
+ end
35
+
36
+ def active?
37
+ !dropped?
38
+ end
39
+
40
+ def resolved!
41
+ self.mode = :resolved
42
+
43
+ to.incoming_edges.each do |edge|
44
+ edge.dropped! unless edge == self
45
+ end
46
+ end
47
+
48
+ def inspect
49
+ "<Edge [#{mode}] #{from.inspect} -> #{to.inspect}>"
50
+ end
51
+ end
52
+
53
+ end
@@ -0,0 +1,13 @@
1
+ # frozen_string_literal: true
2
+
3
+ module EnumMachine
4
+
5
+ class Machine
6
+
7
+ include EnumMachineContrib::HasDecisionTree
8
+
9
+ end
10
+
11
+ class InvalidTransitionGraph < StandardError; end
12
+
13
+ end
@@ -0,0 +1,15 @@
1
+ # frozen_string_literal: true
2
+
3
+ module EnumMachineContrib
4
+ module HasDecisionTree
5
+
6
+ def decision_tree
7
+ start_values = @transitions.keys - @transitions.values.flatten.uniq
8
+ raise EnumMachine::InvalidTransitionGraph, 'There is no start value' if start_values.empty?
9
+ raise EnumMachine::InvalidTransitionGraph, 'Multiple graphs detected' if start_values.size > 1
10
+
11
+ DecisionGraph.new(@transitions).decision_tree
12
+ end
13
+
14
+ end
15
+ end
@@ -0,0 +1,7 @@
1
+ # frozen_string_literal: true
2
+
3
+ module EnumMachineContrib
4
+
5
+ VERSION = '0.1.0'
6
+
7
+ end
@@ -0,0 +1,88 @@
1
+ # frozen_string_literal: true
2
+
3
+ module EnumMachineContrib
4
+
5
+ Vertex =
6
+ Struct.new(:value) do
7
+ attr_accessor :mode, :incoming_edges, :outcoming_edges, :level
8
+
9
+ VERTEX_MODES = %i[plain dropped combined cycled].freeze # rubocop:disable Lint/ConstantDefinitionInBlock
10
+
11
+ def initialize(value)
12
+ self.value = value
13
+ self.outcoming_edges = Set.new
14
+ self.incoming_edges = Set.new
15
+
16
+ plain!
17
+ end
18
+
19
+ VERTEX_MODES.each do |mode|
20
+ class_eval <<-RUBY, __FILE__, __LINE__ + 1
21
+ # def combined!
22
+ # self.mode = :combined
23
+ # end
24
+ # def combined?
25
+ # self.mode == :combined
26
+ # end
27
+
28
+ def #{mode}!
29
+ self.mode = :#{mode}
30
+ end
31
+ def #{mode}?
32
+ self.mode == :#{mode}
33
+ end
34
+ RUBY
35
+ end
36
+
37
+ def active?
38
+ !dropped?
39
+ end
40
+
41
+ def dropped!
42
+ return if dropped?
43
+
44
+ self.mode = :dropped
45
+
46
+ incoming_edges.each(&:dropped!)
47
+ outcoming_edges.each(&:dropped!)
48
+ end
49
+
50
+ def add_edge(to_vertex)
51
+ new_edge = Edge.new(self, to_vertex)
52
+
53
+ outcoming_edges << new_edge
54
+ to_vertex.incoming_edges << new_edge
55
+
56
+ new_edge
57
+ end
58
+
59
+ def self.replace!(replacing_vertexes)
60
+ new_vertex = Vertex[replacing_vertexes.flat_map(&:value)]
61
+
62
+ replacing_vertexes.each do |replacing_vertex|
63
+ replacing_vertex.incoming_edges.each do |edge|
64
+ next unless edge.active?
65
+ next if replacing_vertexes.include?(edge.from)
66
+
67
+ edge.from.add_edge(new_vertex)
68
+ end
69
+
70
+ replacing_vertex.outcoming_edges.filter_map do |edge|
71
+ next unless edge.active?
72
+ next if replacing_vertexes.include?(edge.to)
73
+
74
+ new_vertex.add_edge(edge.to)
75
+ end
76
+
77
+ replacing_vertex.dropped!
78
+ end
79
+
80
+ new_vertex
81
+ end
82
+
83
+ def inspect
84
+ "<Vertex [#{mode}] value=#{value || 'nil'}>"
85
+ end
86
+ end
87
+
88
+ end
@@ -0,0 +1,17 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'enum_machine'
4
+ require 'active_support/core_ext/enumerable'
5
+ require 'active_support/core_ext/array/wrap'
6
+
7
+ require 'enum_machine_contrib/version'
8
+
9
+ module EnumMachineContrib
10
+
11
+ autoload :HasDecisionTree, 'enum_machine_contrib/has_decision_tree'
12
+ autoload :DecisionGraph, 'enum_machine_contrib/decision_graph'
13
+ autoload :DecisionTree, 'enum_machine_contrib/decision_tree'
14
+ autoload :Vertex, 'enum_machine_contrib/vertex'
15
+ autoload :Edge, 'enum_machine_contrib/edge'
16
+
17
+ end
data/states.png ADDED
Binary file
metadata ADDED
@@ -0,0 +1,111 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: enum_machine-contrib
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.0
5
+ platform: ruby
6
+ authors:
7
+ - Sergei Malykh
8
+ autorequire:
9
+ bindir: exe
10
+ cert_chain: []
11
+ date: 2023-03-14 00:00:00.000000000 Z
12
+ dependencies:
13
+ - !ruby/object:Gem::Dependency
14
+ name: activesupport
15
+ requirement: !ruby/object:Gem::Requirement
16
+ requirements:
17
+ - - ">="
18
+ - !ruby/object:Gem::Version
19
+ version: '0'
20
+ type: :runtime
21
+ prerelease: false
22
+ version_requirements: !ruby/object:Gem::Requirement
23
+ requirements:
24
+ - - ">="
25
+ - !ruby/object:Gem::Version
26
+ version: '0'
27
+ - !ruby/object:Gem::Dependency
28
+ name: enum_machine
29
+ requirement: !ruby/object:Gem::Requirement
30
+ requirements:
31
+ - - ">="
32
+ - !ruby/object:Gem::Version
33
+ version: '0'
34
+ type: :runtime
35
+ prerelease: false
36
+ version_requirements: !ruby/object:Gem::Requirement
37
+ requirements:
38
+ - - ">="
39
+ - !ruby/object:Gem::Version
40
+ version: '0'
41
+ - !ruby/object:Gem::Dependency
42
+ name: ruby-graphviz
43
+ requirement: !ruby/object:Gem::Requirement
44
+ requirements:
45
+ - - ">="
46
+ - !ruby/object:Gem::Version
47
+ version: '0'
48
+ type: :runtime
49
+ prerelease: false
50
+ version_requirements: !ruby/object:Gem::Requirement
51
+ requirements:
52
+ - - ">="
53
+ - !ruby/object:Gem::Version
54
+ version: '0'
55
+ description:
56
+ email:
57
+ - xronos.i.am@gmail.com
58
+ executables: []
59
+ extensions: []
60
+ extra_rdoc_files: []
61
+ files:
62
+ - ".rspec"
63
+ - ".rubocop.yml"
64
+ - CHANGELOG.md
65
+ - CODE_OF_CONDUCT.md
66
+ - Gemfile
67
+ - Gemfile.lock
68
+ - LICENSE
69
+ - LICENSE.txt
70
+ - README.md
71
+ - Rakefile
72
+ - enum_machine-contrib.gemspec
73
+ - lib/enum_machine-contrib.rb
74
+ - lib/enum_machine_contrib.rb
75
+ - lib/enum_machine_contrib/decision_graph.rb
76
+ - lib/enum_machine_contrib/decision_tree.rb
77
+ - lib/enum_machine_contrib/edge.rb
78
+ - lib/enum_machine_contrib/enum_machine.rb
79
+ - lib/enum_machine_contrib/has_decision_tree.rb
80
+ - lib/enum_machine_contrib/version.rb
81
+ - lib/enum_machine_contrib/vertex.rb
82
+ - states.png
83
+ homepage: https://github.com/corp-gp/enum_machine-contrib
84
+ licenses:
85
+ - MIT
86
+ metadata:
87
+ allowed_push_host: https://rubygems.org
88
+ homepage_uri: https://github.com/corp-gp/enum_machine-contrib
89
+ source_code_uri: https://github.com/corp-gp/enum_machine-contrib
90
+ changelog_uri: https://github.com/corp-gp/enum_machine-contrib/CHANGELOG.md
91
+ rubygems_mfa_required: 'true'
92
+ post_install_message:
93
+ rdoc_options: []
94
+ require_paths:
95
+ - lib
96
+ required_ruby_version: !ruby/object:Gem::Requirement
97
+ requirements:
98
+ - - ">="
99
+ - !ruby/object:Gem::Version
100
+ version: 2.6.0
101
+ required_rubygems_version: !ruby/object:Gem::Requirement
102
+ requirements:
103
+ - - ">="
104
+ - !ruby/object:Gem::Version
105
+ version: '0'
106
+ requirements: []
107
+ rubygems_version: 3.4.6
108
+ signing_key:
109
+ specification_version: 4
110
+ summary: extensions and tools for enum_machine
111
+ test_files: []