rule_box 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.
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: 0a011e4b78807c6886b9459bf0a2e7d5b189529f89afaaf6af031c53e2a020b2
4
+ data.tar.gz: bd2bb85082c2f97fde224cc3c56442408ed7a55f9fd025a7bd72acaa637d5777
5
+ SHA512:
6
+ metadata.gz: a70aa27e89b761ccac09eba4ee77a5630eb74122bb7ace331b05ffd0c0480f81da65f641ad76f72a563665fd3a1af590af046e54d6301ed3d015fcb5773a31f2
7
+ data.tar.gz: 1cbff9c41ad00c46f69164558d057b687428b4d7ebd1ad403038d099f4c25a37b61dfd5a4520ae6a6818635122925dd9943a2cde300eb90183cf23054ef692ca
@@ -0,0 +1,13 @@
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
+ /.rakeTasks
13
+ /*.gem
data/.rspec ADDED
@@ -0,0 +1,3 @@
1
+ --format documentation
2
+ --color
3
+ --require spec_helper
@@ -0,0 +1,6 @@
1
+ ---
2
+ language: ruby
3
+ cache: bundler
4
+ rvm:
5
+ - 2.5.1
6
+ before_install: gem install bundler -v 2.1.4
@@ -0,0 +1,74 @@
1
+ # Contributor Covenant Code of Conduct
2
+
3
+ ## Our Pledge
4
+
5
+ In the interest of fostering an open and welcoming environment, we as
6
+ contributors and maintainers pledge to making participation in our project and
7
+ our community a harassment-free experience for everyone, regardless of age, body
8
+ size, disability, ethnicity, gender identity and expression, level of experience,
9
+ nationality, personal appearance, race, religion, or sexual identity and
10
+ orientation.
11
+
12
+ ## Our Standards
13
+
14
+ Examples of behavior that contributes to creating a positive environment
15
+ include:
16
+
17
+ * Using welcoming and inclusive language
18
+ * Being respectful of differing viewpoints and experiences
19
+ * Gracefully accepting constructive criticism
20
+ * Focusing on what is best for the community
21
+ * Showing empathy towards other community members
22
+
23
+ Examples of unacceptable behavior by participants include:
24
+
25
+ * The use of sexualized language or imagery and unwelcome sexual attention or
26
+ advances
27
+ * Trolling, insulting/derogatory comments, and personal or political attacks
28
+ * Public or private harassment
29
+ * Publishing others' private information, such as a physical or electronic
30
+ address, without explicit permission
31
+ * Other conduct which could reasonably be considered inappropriate in a
32
+ professional setting
33
+
34
+ ## Our Responsibilities
35
+
36
+ Project maintainers are responsible for clarifying the standards of acceptable
37
+ behavior and are expected to take appropriate and fair corrective action in
38
+ response to any instances of unacceptable behavior.
39
+
40
+ Project maintainers have the right and responsibility to remove, edit, or
41
+ reject comments, commits, code, wiki edits, issues, and other contributions
42
+ that are not aligned to this Code of Conduct, or to ban temporarily or
43
+ permanently any contributor for other behaviors that they deem inappropriate,
44
+ threatening, offensive, or harmful.
45
+
46
+ ## Scope
47
+
48
+ This Code of Conduct applies both within project spaces and in public spaces
49
+ when an individual is representing the project or its community. Examples of
50
+ representing a project or community include using an official project e-mail
51
+ address, posting via an official social media account, or acting as an appointed
52
+ representative at an online or offline event. Representation of a project may be
53
+ further defined and clarified by project maintainers.
54
+
55
+ ## Enforcement
56
+
57
+ Instances of abusive, harassing, or otherwise unacceptable behavior may be
58
+ reported by contacting the project team at ralphsbaesso@gmail.com. All
59
+ complaints will be reviewed and investigated and will result in a response that
60
+ is deemed necessary and appropriate to the circumstances. The project team is
61
+ obligated to maintain confidentiality with regard to the reporter of an incident.
62
+ Further details of specific enforcement policies may be posted separately.
63
+
64
+ Project maintainers who do not follow or enforce the Code of Conduct in good
65
+ faith may face temporary or permanent repercussions as determined by other
66
+ members of the project's leadership.
67
+
68
+ ## Attribution
69
+
70
+ This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4,
71
+ available at [https://contributor-covenant.org/version/1/4][version]
72
+
73
+ [homepage]: https://contributor-covenant.org
74
+ [version]: https://contributor-covenant.org/version/1/4/
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 rule_box.gemspec
6
+ gemspec
7
+
8
+ gem 'rake', '~> 12.0'
9
+ gem 'rspec', '~> 3.0'
@@ -0,0 +1,34 @@
1
+ PATH
2
+ remote: .
3
+ specs:
4
+ rule_box (0.1.0)
5
+
6
+ GEM
7
+ remote: https://rubygems.org/
8
+ specs:
9
+ diff-lcs (1.4.4)
10
+ rake (12.3.3)
11
+ rspec (3.9.0)
12
+ rspec-core (~> 3.9.0)
13
+ rspec-expectations (~> 3.9.0)
14
+ rspec-mocks (~> 3.9.0)
15
+ rspec-core (3.9.2)
16
+ rspec-support (~> 3.9.3)
17
+ rspec-expectations (3.9.2)
18
+ diff-lcs (>= 1.2.0, < 2.0)
19
+ rspec-support (~> 3.9.0)
20
+ rspec-mocks (3.9.1)
21
+ diff-lcs (>= 1.2.0, < 2.0)
22
+ rspec-support (~> 3.9.0)
23
+ rspec-support (3.9.3)
24
+
25
+ PLATFORMS
26
+ ruby
27
+
28
+ DEPENDENCIES
29
+ rake (~> 12.0)
30
+ rspec (~> 3.0)
31
+ rule_box!
32
+
33
+ BUNDLED WITH
34
+ 2.1.4
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2020 ralph
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.
@@ -0,0 +1,203 @@
1
+ # 🧰 RuleBox
2
+
3
+ This gem is focused in giving a strong and concrete way to manage your business rules, mixing the best of both worlds in Facade and Strategy, bringing you a simplified way to apply these _Design Patterns_ into your project.
4
+
5
+ #### What is Facade?
6
+
7
+ Facade is nothing more than an object that serves as a front-facing interface, abstracting more complex underlying or structural code.
8
+ Benefits:
9
+
10
+ - It improves your readability and usability.
11
+ - It provides a context-specific interface to more generic functionality.
12
+ - It hides the complexities of the larger system and provides a simpler interface to the client.
13
+
14
+ #### What is Strategy?
15
+
16
+ Strategy is a behavioral design pattern that lets you define a family of algorithms, put each of them into a separate class, and make their objects reusable.
17
+
18
+ Instead of the object having all the business rules inside the model, they will be alocated in separate classes, which will be considered now as _strategies_. These classes could be used inside other objects as well.
19
+
20
+ ## Installation
21
+
22
+ Add this line to your application's Gemfile:
23
+
24
+ ```ruby
25
+ gem 'rule_box'
26
+ ```
27
+
28
+ And then execute:
29
+
30
+ $ bundle install
31
+
32
+ Or install it yourself as:
33
+
34
+ $ gem install rule_box
35
+
36
+ ## Usage
37
+
38
+ To get started using business rules inside your **model** with RuleBox, they must have a business rules list.
39
+
40
+ #### 1. Creating the business rules (Strategy).
41
+
42
+ Create a file named *check_name.rb*.
43
+
44
+ In this class, it should inherit from Strategy class and overwrite its method *process*.
45
+
46
+ Then, inside this method, it goes your business rule logic.
47
+
48
+
49
+ ```ruby
50
+ require 'rulebox/strategy'
51
+
52
+ class CheckName < RuleBox::Strategy
53
+ def process
54
+ # your code here
55
+ end
56
+ end
57
+ ```
58
+
59
+ There are some *helpers* in the class *Strategy* that will help you out.
60
+
61
+ ```ruby
62
+ strategy.model # returns "Model"
63
+ strategy.set_status # sets the light: [:red, :yellow, :green]
64
+ strategy.add_error # adds an error message
65
+ ```
66
+
67
+ So, your file *check_name.rb* should look like this:
68
+
69
+ ```ruby
70
+ require 'rulebox/strategy'
71
+
72
+ class CheckName < RuleBox::Strategy
73
+ def process
74
+ user = model
75
+ if user.name.nil?
76
+ add_error 'Name cannot be empty'
77
+ set_status :red
78
+ elsif user.name.size < 4
79
+ add_error 'Name must contain at least 4 characters'
80
+ set_status :red
81
+ end
82
+ end
83
+ end
84
+ ```
85
+
86
+ #### 2. Mapping the business rules in the Model
87
+ ```ruby
88
+ require 'rule_box/mapper'
89
+ require_relative 'validate_name'
90
+
91
+ class User
92
+ include RuleBox::Mapper
93
+ attr_accessor :name
94
+
95
+ # list of business rules
96
+ rules_of_insert Rules::CheckName
97
+
98
+ end
99
+ ```
100
+
101
+ #### 3. Call RuleBox
102
+
103
+ ```ruby
104
+ require 'rule_box/facade'
105
+
106
+ user = User.new
107
+ facade = RuleBox::Facade.new
108
+ facade.insert user
109
+ puts facade.status # :red
110
+ puts facade.errors # ["Name cannot be empty."]
111
+
112
+ user = User.new
113
+ user.name = 'Bob'
114
+ facade = RuleBox::Facade.new
115
+ facade.insert user
116
+ puts facade.status # :red
117
+ puts facade.errors # ["Name must contain at least 4 characters"]
118
+
119
+ user = User.new
120
+ user.name = 'Alex'
121
+ facade = RuleBox::Facade.new
122
+ facade.insert user
123
+ puts facade.status # :green
124
+ puts facade.errors # []
125
+
126
+ ```
127
+
128
+ #### Applying multiple business rules
129
+
130
+ ```ruby
131
+ class CheckName < RuleBox::Strategy
132
+ def process
133
+ user = model
134
+
135
+ if user.name.nil?
136
+ add_error 'Name cannot be empty.'
137
+ set_status :red
138
+ elsif user.name.size < 4
139
+ add_error 'Name must contain at least 4 characters'
140
+ set_status :red
141
+ end
142
+ end
143
+ end
144
+
145
+ class CheckAge < RuleBox::Strategy
146
+ def process
147
+ user = model
148
+
149
+ if !user.age.is_a? Integer
150
+ add_error '"Age must be an integer"'
151
+ set_status :red
152
+ elsif user.age < 18
153
+ add_error 'Age cannot be under 18'
154
+ set_status :red
155
+ end
156
+ end
157
+ end
158
+
159
+ class SaveModel < RuleBox::Strategy
160
+ def process
161
+ if status == :green
162
+ # DAO.persist_model(model)
163
+ end
164
+ end
165
+ end
166
+
167
+ # Class example with multiple business rules
168
+ class User
169
+ include RuleBox::Mapper
170
+ attr_accessor :name, :age
171
+
172
+ rules_of_insert Rules::CheckName, Rules::CheckAge, Rules::SaveModel
173
+
174
+ end
175
+
176
+ ```
177
+
178
+
179
+ ## Development
180
+
181
+ Once in development mode, it can display the steps that took place in Facade.
182
+
183
+ ```ruby
184
+ user = User.new
185
+ user.name = 'John Wick'
186
+ user.age = 19
187
+
188
+ facade = RuleBox::Facade.new
189
+ facade.show_steps = true
190
+ facade.insert user
191
+
192
+ # Log Output
193
+ # [2020-07-29T08:09:00.212-03:00] { method: insert, model: User, args: {} }
194
+ # [2020-07-29T08:09:00.212-03:00] amount of rules 3
195
+ # [2020-07-29T08:09:00.212-03:00] executing of rule: Rules::CheckName.
196
+ # [2020-07-29T08:09:00.212-03:00] executing of rule: Rules::CheckAge.
197
+ # [2020-07-29T08:09:00.212-03:00] executing of rule: Rules::SaveModel.
198
+ # [2020-07-29T08:09:00.212-03:00] finalized the process on the facade.
199
+ ```
200
+
201
+ ## License
202
+
203
+ The gem is available as open source under the terms of the [MIT License](https://opensource.org/licenses/MIT).
@@ -0,0 +1,201 @@
1
+ # RuleBox
2
+
3
+ Esta gem tem como objetivo fornecer uma maneira forte e concreta de gerenciar suas regras de negócios, combinando o melhor dos dois mundos em Facade e Strategy, trazendo a você uma maneira simplificada de aplicar esses _Design Patterns_ em seu projeto.
4
+
5
+ #### O que é Facade?
6
+
7
+ Facade nada mais é do que um objeto que funciona como uma interface frontal, abstraindo código estrutural ou subjacente mais complexo.
8
+ Benefícios:
9
+
10
+ - Melhora a sua legibilidade e usabilidade.
11
+ - Ele fornece uma interface específica de contexto para uma funcionalidade mais genérica.
12
+ - Ele oculta as complexidades do sistema maior e fornece uma interface mais simples para o cliente.
13
+
14
+ #### O que é Strategy?
15
+
16
+ Strategy é um padrão de design comportamental que permite definir uma família de algoritmos, colocar cada um deles em uma classe separada e tornar seus objetos reutilizáveis.
17
+
18
+ Em vez de o objeto ter todas as regras de negócio dentro do model, elas serão alocadas em classes separadas, que serão consideradas agora como _strategies_. Essas classes também podem ser usadas dentro de outros objetos.
19
+
20
+ ## Instalação
21
+
22
+ Adicione esta linha ao Gemfile do seu aplicativo:
23
+
24
+ ```ruby
25
+ gem 'rule_box'
26
+ ```
27
+
28
+ Então execute:
29
+
30
+ $ bundle install
31
+
32
+ Ou instale você mesmo:
33
+
34
+ $ gem install rule_box
35
+
36
+ ## Utilização
37
+
38
+ Para começar a usar regras de negócios dentro de seu **model** com RuleBox, eles devem possuir uma lista de regras de negócios.
39
+
40
+ #### 1. Criando regra de negócio (Strategy).
41
+
42
+ Crie um arquivo chamado *check_name.rb*.
43
+
44
+ Nesta classe, ele deve herdar da classe Strategy e substituir seu método *process*.
45
+
46
+ Então, dentro desse método, insira sua lógica de regra de negócios.
47
+
48
+ ```ruby
49
+ require 'rule_box/strategy'
50
+
51
+ class CheckName < RuleBox::Strategy
52
+ def process
53
+ # sua lógica aqui
54
+ end
55
+ end
56
+ ```
57
+
58
+ Existem alguns *helpers* na classe *Strategy* que irão ajudá-lo.
59
+
60
+ ```ruby
61
+ strategy.model # Retorna o "Model"
62
+ strategy.set_status # Seta o valor semáforo: [:red, :yellow, :green]
63
+ strategy.add_error # Adiciona uma mensagem de erro
64
+ ```
65
+
66
+ Então, seu arquivo *check_name.rb* deverá ficar assim:
67
+
68
+ ```ruby
69
+ require 'rule_box/strategy'
70
+
71
+ class CheckName < RuleBox::Strategy
72
+ def process
73
+ user = model
74
+ if user.name.nil?
75
+ add_error 'Nome não pode ficar em branco'
76
+ set_status :red
77
+ elsif user.name.size < 4
78
+ add_error 'Nome deve conter pelo menos 4 caracteres'
79
+ set_status :red
80
+ end
81
+ end
82
+ end
83
+ ```
84
+
85
+ #### 2. Mapear as regras de negócio no Model
86
+ ```ruby
87
+ require 'rule_box/mapper'
88
+ require_relative 'validate_name'
89
+
90
+ class User
91
+ include RuleBox::Mapper
92
+ attr_accessor :name
93
+
94
+ # lista de regras de negócio
95
+ rules_of_insert Rules::CheckName
96
+
97
+ end
98
+ ```
99
+
100
+ #### 3. Chamar RuleBox
101
+ ```ruby
102
+ require 'rule_box/facade'
103
+
104
+ user = User.new
105
+ facade = Rulebox::Facade.new
106
+ facade.insert user
107
+ puts facade.status # :red
108
+ puts facade.errors # ["Nome não pode ficar em branco"]
109
+
110
+ user = User.new
111
+ user.name = 'Ana'
112
+ facade = Rulebox::Facade.new
113
+ facade.insert user
114
+ puts facade.status # :red
115
+ puts facade.errors # ["Nome deve conter pelo menos 4 caracteres"]
116
+
117
+ user = User.new
118
+ user.name = 'Alex'
119
+ facade = Rulebox::Facade.new
120
+ facade.insert user
121
+ puts facade.status # :green
122
+ puts facade.errors # []
123
+
124
+ ```
125
+
126
+ #### Aplicando multiplos regras de negócio
127
+
128
+ ```ruby
129
+ class CheckName < RuleBox::Strategy
130
+ def process
131
+ user = model
132
+
133
+ if user.name.nil?
134
+ add_error 'Nome não pode ficar em branco'
135
+ set_status :red
136
+ elsif user.name.size < 4
137
+ add_error 'Nome deve conter pelo menos 4 caracteres'
138
+ set_status :red
139
+ end
140
+ end
141
+ end
142
+
143
+ class CheckAge < RuleBox::Strategy
144
+ def process
145
+ user = model
146
+
147
+ if !user.age.is_a? Integer
148
+ add_error 'Idade precisa ser um número inteiro'
149
+ set_status :red
150
+ elsif user.age < 18
151
+ add_error 'Deve ser maior que 18'
152
+ set_status :red
153
+ end
154
+ end
155
+ end
156
+
157
+ class SaveModel < RuleBox::Strategy
158
+ def process
159
+ if status == :green
160
+ # DAO.persist_model(model)
161
+ end
162
+ end
163
+ end
164
+
165
+ # Exemplo de classe com múltiplas regras de negócio
166
+ class User
167
+ include RuleBox::Mapper
168
+ attr_accessor :name, :age
169
+
170
+ rules_of_insert Rules::CheckName, Rules::CheckAge, Rules::SaveModel
171
+
172
+ end
173
+
174
+ ```
175
+
176
+
177
+ ## Desenvolvimento
178
+
179
+ Uma vez no modo de desenvolvimento, ele pode exibir as etapas (steps) que ocorreram no Facade.
180
+
181
+ ```ruby
182
+ user = User.new
183
+ user.name = 'Carlos'
184
+ user.age = 19
185
+
186
+ facade = RuleBox::Facade.new
187
+ facade.show_steps = true
188
+ facade.insert user
189
+
190
+ # Saída do Log
191
+ # [2020-07-29T08:09:00.212-03:00] { method: insert, model: User, args: {} }
192
+ # [2020-07-29T08:09:00.212-03:00] amount of rules 3
193
+ # [2020-07-29T08:09:00.212-03:00] executing of rule: Rules::CheckName.
194
+ # [2020-07-29T08:09:00.212-03:00] executing of rule: Rules::CheckAge.
195
+ # [2020-07-29T08:09:00.212-03:00] executing of rule: Rules::SaveModel.
196
+ # [2020-07-29T08:09:00.212-03:00] finalized the process on the facade.
197
+ ```
198
+
199
+ ## License
200
+
201
+ The gem is available as open source under the terms of the [MIT License](https://opensource.org/licenses/MIT).
@@ -0,0 +1,8 @@
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
+ task default: :spec
@@ -0,0 +1,15 @@
1
+ #!/usr/bin/env ruby
2
+ # frozen_string_literal: true
3
+
4
+ require 'bundler/setup'
5
+ require 'rule_box'
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__)
@@ -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
@@ -0,0 +1,25 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'time'
4
+ require 'json'
5
+
6
+ module RuleBox
7
+ class Error < StandardError; end
8
+
9
+ class << self
10
+
11
+ def show_mapped_classes
12
+ RuleBox::Mapper.mapped.to_a
13
+ end
14
+ end
15
+
16
+ end
17
+
18
+ require 'rule_box/facade'
19
+ require 'rule_box/getter'
20
+ require 'rule_box/hash'
21
+ require 'rule_box/mapper'
22
+ require 'rule_box/proxy'
23
+ require 'rule_box/strategy'
24
+ require 'rule_box/util'
25
+ require 'rule_box/version'
@@ -0,0 +1,190 @@
1
+ # frozen_string_literal: true
2
+
3
+ class RuleBox::Facade
4
+ attr_reader :model, :status, :data, :bucket, :errors, :steps, :executed
5
+ attr_accessor :show_steps
6
+
7
+ def initialize(**dependencies)
8
+ errors = []
9
+ settings.dependencies.each do |key, block|
10
+ begin
11
+ if dependencies.key? key
12
+ value = dependencies[key]
13
+ block&.call(value, errors)
14
+ else
15
+ errors << "missing keyword: #{key}"
16
+ end
17
+ rescue StandardError => e
18
+ errors << e.message
19
+ end
20
+ end
21
+
22
+ raise errors.join("\n") unless errors.empty?
23
+
24
+ dependencies.each { |key, value| keys["current_#{key}".to_sym] = value }
25
+ @executed = false
26
+ @show_steps = settings.show_steps
27
+ end
28
+
29
+ def insert(model, **args)
30
+ execute(:insert, model, args)
31
+ end
32
+
33
+ def select(model, **args)
34
+ execute(:select, model, args)
35
+ end
36
+
37
+ def update(model, **args)
38
+ execute(:update, model, args)
39
+ end
40
+
41
+ def delete(model, **args)
42
+ execute(:delete, model, args)
43
+ end
44
+
45
+ def attributes
46
+ attrs = {}
47
+ %i[model status data bucket executed errors steps].each do |key|
48
+ value = send key
49
+ attrs[key] = value
50
+ end
51
+ attrs
52
+ end
53
+
54
+ def to_json(**args)
55
+ JSON.generate(as_json(args), args)
56
+ end
57
+
58
+ def as_json(**options)
59
+ options.key?(:root) ? { self.class.name.to_sym => attributes } : attributes
60
+ end
61
+
62
+ def to_s
63
+ as_json(root: true).to_s
64
+ end
65
+
66
+ private
67
+
68
+ def method_missing(method, *parameters)
69
+ super if parameters.empty?
70
+ super if method.to_s.end_with? '='
71
+
72
+ model = parameters[0]
73
+ args = parameters[1] || {}
74
+ execute(method, model, args)
75
+ end
76
+
77
+ def respond_to_missing?(method, _include_private = false)
78
+ return false if @executed || method.to_s.end_with?('=')
79
+
80
+ true
81
+ end
82
+
83
+ def execute(method, model, **args)
84
+ raise 'Process already executed' if @executed
85
+
86
+ @executed = true
87
+ @status = :green
88
+ @bucket = RuleBox::Hash.new
89
+ args.each { |key, value| bucket[key] = value }
90
+ pre_process(method, model)
91
+ end
92
+
93
+ def pre_process(method, model)
94
+ @model = model
95
+ class_name = check_class_model
96
+ @errors = []
97
+ @steps = []
98
+
99
+ add_step "{ method: #{method}, model: #{class_name}, args: #{bucket} }"
100
+ strategies = class_name.strategies(method)&.map { |strategy| strategy.new(self) }
101
+ unless strategies
102
+ raise "class [#{class_name}] without mapped rules to [#{method}]'"
103
+ end
104
+
105
+ process(strategies)
106
+ end
107
+
108
+ def process(strategies)
109
+ add_step "amount of rules #{strategies.count}"
110
+
111
+ strategies.each do |strategy|
112
+ add_step "executing of rule: #{strategy.class.name}."
113
+ strategy.process
114
+
115
+ break if status == :red
116
+ end
117
+ rescue Exception => e
118
+ errors << settings.default_error_message
119
+ @status = :red
120
+ block = settings.resolve
121
+ block.call(e, RuleBox::Proxy.new(self)) if block.is_a? Proc
122
+ ensure
123
+ add_step 'finalized the process on the facade.'
124
+ return self
125
+ end
126
+
127
+ def settings
128
+ RuleBox::Facade.settings
129
+ end
130
+
131
+ def add_step(value)
132
+ new_value = "[#{DateTime.now.strftime('%FT%T.%L%:z')}] #{value}"
133
+ puts new_value if show_steps || settings.show_steps
134
+ steps << new_value
135
+ end
136
+
137
+ def check_class_model
138
+ if model.is_a?(Class) || model.is_a?(Module)
139
+ model
140
+ elsif model.is_a?(Symbol) || model.is_a?(String)
141
+ Object.const_get RuleBox::Util.camelize(model.to_s)
142
+ else
143
+ Object.const_get model.class.name
144
+ end
145
+ end
146
+
147
+ def keys
148
+ @keys ||= {}
149
+ end
150
+
151
+ # class Methods
152
+ class << self
153
+ def configure
154
+ yield(settings) if block_given?
155
+ end
156
+
157
+ def clear_configuration
158
+ @settings = Settings.new
159
+ end
160
+
161
+ def settings
162
+ @settings ||= Settings.new
163
+ end
164
+
165
+ private
166
+
167
+ class Settings
168
+ attr_reader :dependencies, :resolve
169
+ attr_writer :default_error_message
170
+ attr_accessor :show_steps
171
+
172
+ def initialize
173
+ @dependencies = {}
174
+ @show_steps = false
175
+ end
176
+
177
+ def add_dependency(key, &block)
178
+ dependencies[key.to_sym] = block
179
+ end
180
+
181
+ def resolver_exception(&block)
182
+ @resolve = block
183
+ end
184
+
185
+ def default_error_message
186
+ @default_error_message || 'unhandled error'
187
+ end
188
+ end
189
+ end
190
+ end
@@ -0,0 +1,67 @@
1
+ # frozen_string_literal: true
2
+
3
+ module RuleBox::Getter
4
+ def initialize(facade)
5
+ raise 'Must pass an "RFacade"' unless facade.is_a? RuleBox::Facade
6
+
7
+ @facade = facade
8
+ end
9
+
10
+ def model
11
+ model = @facade.model
12
+ if model.is_a?(Class) || model.is_a?(Module)
13
+ model.to_s
14
+ else
15
+ model.clone
16
+ end
17
+ end
18
+
19
+ def status
20
+ @facade.status
21
+ end
22
+
23
+ def data
24
+ @facade.data.clone
25
+ end
26
+
27
+ def bucket
28
+ @facade.bucket.clone
29
+ end
30
+
31
+ def errors
32
+ @facade.errors.clone
33
+ end
34
+
35
+ def steps
36
+ @facade.steps.clone
37
+ end
38
+
39
+ def executed
40
+ @facade.executed
41
+ end
42
+
43
+ def to_json(**args)
44
+ @facade.to_json(args)
45
+ end
46
+
47
+ def as_json(**options)
48
+ options.key?(:root) ? { self.class.name.to_sym => @facade.attributes } : @facade.attributes
49
+ end
50
+
51
+ def to_s
52
+ @facade.as_json(root: true).to_s
53
+ end
54
+
55
+ def respond_to_missing?(*several_variants)
56
+ super unless method.to_s.start_with? 'current_'
57
+ end
58
+
59
+ private
60
+
61
+ def method_missing(method)
62
+ super unless method.to_s.start_with? 'current_'
63
+
64
+ keys = @facade.send :keys
65
+ keys[method].clone
66
+ end
67
+ end
@@ -0,0 +1,11 @@
1
+ # frozen_string_literal: true
2
+
3
+ class RuleBox::Hash < Hash
4
+ def []=(key, value)
5
+ super(key.to_sym, value)
6
+ end
7
+
8
+ def [](key)
9
+ super(key.to_sym)
10
+ end
11
+ end
@@ -0,0 +1,62 @@
1
+ # frozen_string_literal: true
2
+
3
+ module RuleBox::Mapper
4
+ def self.included(klass)
5
+ klass.extend(ClassMethods)
6
+ mapped << klass
7
+ end
8
+
9
+ def self.mapped
10
+ @mapped ||= Set.new
11
+ end
12
+
13
+ module ClassMethods
14
+ def rules_of_insert(*rules)
15
+ add_rules :insert, rules
16
+ end
17
+
18
+ def rules_of_update(*rules)
19
+ add_rules :update, rules
20
+ end
21
+
22
+ def rules_of_delete(*rules)
23
+ add_rules :delete, rules
24
+ end
25
+
26
+ def rules_of_select(*rules)
27
+ add_rules :select, rules
28
+ end
29
+
30
+ def rules_of(method, *rules)
31
+ add_rules method.to_sym, rules
32
+ end
33
+
34
+ def strategies(method)
35
+ current_rules[method]
36
+ end
37
+
38
+ def show_strategies
39
+ current_rules.map do |method, strategies|
40
+ {
41
+ method: method,
42
+ strategies: strategies.map do |strategy|
43
+ {
44
+ name: strategy.name,
45
+ description: strategy.description
46
+ }
47
+ end
48
+ }
49
+ end
50
+ end
51
+
52
+ private
53
+
54
+ def add_rules(method, rules)
55
+ current_rules[method] = rules
56
+ end
57
+
58
+ def current_rules
59
+ @current_rules ||= {}
60
+ end
61
+ end
62
+ end
@@ -0,0 +1,5 @@
1
+ # frozen_string_literal: true
2
+
3
+ class RuleBox::Proxy
4
+ include RuleBox::Getter
5
+ end
@@ -0,0 +1,45 @@
1
+ # frozen_string_literal: true
2
+
3
+ class RuleBox::Strategy
4
+ include RuleBox::Getter
5
+
6
+ def process
7
+ raise 'Must implement this method'
8
+ end
9
+
10
+ def set_status(status)
11
+ @facade.instance_variable_set :@status, status
12
+ end
13
+
14
+ def add_error(msg)
15
+ if msg.is_a? Array
16
+ @facade.errors.concat(msg)
17
+ else
18
+ @facade.errors << msg
19
+ end
20
+ end
21
+
22
+ def model
23
+ @facade.model
24
+ end
25
+
26
+ def data
27
+ @facade.data
28
+ end
29
+
30
+ def data=(data)
31
+ @facade.instance_variable_set :@data, data
32
+ end
33
+
34
+ def bucket
35
+ @facade.bucket
36
+ end
37
+
38
+ class << self
39
+ attr_reader :description
40
+
41
+ def desc(description)
42
+ @description = description
43
+ end
44
+ end
45
+ end
@@ -0,0 +1,14 @@
1
+ # frozen_string_literal: true
2
+
3
+ module RuleBox::Util
4
+ class << self
5
+ def camelize(string)
6
+ strings = string.split('_')
7
+ new_string = ''
8
+ strings.each do |word|
9
+ new_string += word[0].upcase + word[1..-1]
10
+ end
11
+ new_string.gsub('/', '::')
12
+ end
13
+ end
14
+ end
@@ -0,0 +1,5 @@
1
+ # frozen_string_literal: true
2
+
3
+ module RuleBox
4
+ VERSION = '0.1.0'
5
+ end
@@ -0,0 +1,31 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative 'lib/rule_box/version'
4
+
5
+ Gem::Specification.new do |spec|
6
+ spec.name = 'rule_box'
7
+ spec.version = RuleBox::VERSION
8
+ spec.authors = ['Ralph Baesso', 'Nathan Meira']
9
+ spec.email = ['ralphsbaesso@gmail.com', 'nathanmeira1@gmail.com']
10
+
11
+ spec.summary = 'RuleBox'
12
+ spec.description = 'Gerenciamento de fluxo de regra de negócio.'
13
+ spec.homepage = 'https://github.com/ralphsbaesso'
14
+ spec.license = 'MIT'
15
+ spec.required_ruby_version = Gem::Requirement.new('>= 2.3.0')
16
+
17
+ # spec.metadata['allowed_push_host'] = "TODO: Set to 'http://mygemserver.com'"
18
+
19
+ spec.metadata['homepage_uri'] = spec.homepage
20
+ spec.metadata['source_code_uri'] = 'https://github.com/ralphsbaesso/rule_box'
21
+ # spec.metadata["changelog_uri"] = "TODO: Put your gem's CHANGELOG.md URL here."
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{^(test|spec|features)/}) }
27
+ end
28
+ spec.bindir = 'exe'
29
+ spec.executables = spec.files.grep(%r{^exe/}) { |f| File.basename(f) }
30
+ spec.require_paths = ['lib']
31
+ end
metadata ADDED
@@ -0,0 +1,70 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: rule_box
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.0
5
+ platform: ruby
6
+ authors:
7
+ - Ralph Baesso
8
+ - Nathan Meira
9
+ autorequire:
10
+ bindir: exe
11
+ cert_chain: []
12
+ date: 2020-09-12 00:00:00.000000000 Z
13
+ dependencies: []
14
+ description: Gerenciamento de fluxo de regra de negócio.
15
+ email:
16
+ - ralphsbaesso@gmail.com
17
+ - nathanmeira1@gmail.com
18
+ executables: []
19
+ extensions: []
20
+ extra_rdoc_files: []
21
+ files:
22
+ - ".gitignore"
23
+ - ".rspec"
24
+ - ".travis.yml"
25
+ - CODE_OF_CONDUCT.md
26
+ - Gemfile
27
+ - Gemfile.lock
28
+ - LICENSE.txt
29
+ - README.md
30
+ - README.pt-br.md
31
+ - Rakefile
32
+ - bin/console
33
+ - bin/setup
34
+ - lib/rule_box.rb
35
+ - lib/rule_box/facade.rb
36
+ - lib/rule_box/getter.rb
37
+ - lib/rule_box/hash.rb
38
+ - lib/rule_box/mapper.rb
39
+ - lib/rule_box/proxy.rb
40
+ - lib/rule_box/strategy.rb
41
+ - lib/rule_box/util.rb
42
+ - lib/rule_box/version.rb
43
+ - rule_box.gemspec
44
+ homepage: https://github.com/ralphsbaesso
45
+ licenses:
46
+ - MIT
47
+ metadata:
48
+ homepage_uri: https://github.com/ralphsbaesso
49
+ source_code_uri: https://github.com/ralphsbaesso/rule_box
50
+ post_install_message:
51
+ rdoc_options: []
52
+ require_paths:
53
+ - lib
54
+ required_ruby_version: !ruby/object:Gem::Requirement
55
+ requirements:
56
+ - - ">="
57
+ - !ruby/object:Gem::Version
58
+ version: 2.3.0
59
+ required_rubygems_version: !ruby/object:Gem::Requirement
60
+ requirements:
61
+ - - ">="
62
+ - !ruby/object:Gem::Version
63
+ version: '0'
64
+ requirements: []
65
+ rubyforge_project:
66
+ rubygems_version: 2.7.7
67
+ signing_key:
68
+ specification_version: 4
69
+ summary: RuleBox
70
+ test_files: []