declarable 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- checksums.yaml +7 -0
- data/.rubocop.yml +8 -0
- data/CHANGELOG.md +5 -0
- data/CODE_OF_CONDUCT.md +132 -0
- data/LICENSE +21 -0
- data/LICENSE.txt +21 -0
- data/README.md +241 -0
- data/Rakefile +8 -0
- data/lib/declarable/action.rb +14 -0
- data/lib/declarable/context.rb +86 -0
- data/lib/declarable/definition.rb +40 -0
- data/lib/declarable/validation_error.rb +6 -0
- data/lib/declarable/validator.rb +43 -0
- data/lib/declarable/version.rb +5 -0
- data/lib/declarable.rb +40 -0
- data/sig/declarable.rbs +4 -0
- metadata +79 -0
checksums.yaml
ADDED
@@ -0,0 +1,7 @@
|
|
1
|
+
---
|
2
|
+
SHA256:
|
3
|
+
metadata.gz: 65997f69dff92cff614bf8104fd3afac40e0155b1ce27af1083c2adfd3f763c3
|
4
|
+
data.tar.gz: ffcff7ffcb9cdf25af8565b6b6b170c79d5c03daef6bcdfeed985014b330b4df
|
5
|
+
SHA512:
|
6
|
+
metadata.gz: 378085e5b8e2b9f52ce0c84e4baf1398a7853b12649a1327a33b76d1ebb549ac85b2fcb6be60accb775b5b2ac11bf5bf441ff40efae3c714da96af36adb52c12
|
7
|
+
data.tar.gz: 5edc110952460206f7e6f78443988ff6fcacfed15c64f375cf068f2f0d8e73bc3c6c9ed176325f15bd80c5b8747aaacebc802e25c1114e5a984c26effaedb1d5
|
data/.rubocop.yml
ADDED
data/CHANGELOG.md
ADDED
data/CODE_OF_CONDUCT.md
ADDED
@@ -0,0 +1,132 @@
|
|
1
|
+
# Contributor Covenant Code of Conduct
|
2
|
+
|
3
|
+
## Our Pledge
|
4
|
+
|
5
|
+
We as members, contributors, and leaders pledge to make participation in our
|
6
|
+
community a harassment-free experience for everyone, regardless of age, body
|
7
|
+
size, visible or invisible disability, ethnicity, sex characteristics, gender
|
8
|
+
identity and expression, level of experience, education, socio-economic status,
|
9
|
+
nationality, personal appearance, race, caste, color, religion, or sexual
|
10
|
+
identity and orientation.
|
11
|
+
|
12
|
+
We pledge to act and interact in ways that contribute to an open, welcoming,
|
13
|
+
diverse, inclusive, and healthy community.
|
14
|
+
|
15
|
+
## Our Standards
|
16
|
+
|
17
|
+
Examples of behavior that contributes to a positive environment for our
|
18
|
+
community include:
|
19
|
+
|
20
|
+
* Demonstrating empathy and kindness toward other people
|
21
|
+
* Being respectful of differing opinions, viewpoints, and experiences
|
22
|
+
* Giving and gracefully accepting constructive feedback
|
23
|
+
* Accepting responsibility and apologizing to those affected by our mistakes,
|
24
|
+
and learning from the experience
|
25
|
+
* Focusing on what is best not just for us as individuals, but for the overall
|
26
|
+
community
|
27
|
+
|
28
|
+
Examples of unacceptable behavior include:
|
29
|
+
|
30
|
+
* The use of sexualized language or imagery, and sexual attention or advances of
|
31
|
+
any kind
|
32
|
+
* Trolling, insulting or derogatory comments, and personal or political attacks
|
33
|
+
* Public or private harassment
|
34
|
+
* Publishing others' private information, such as a physical or email address,
|
35
|
+
without their explicit permission
|
36
|
+
* Other conduct which could reasonably be considered inappropriate in a
|
37
|
+
professional setting
|
38
|
+
|
39
|
+
## Enforcement Responsibilities
|
40
|
+
|
41
|
+
Community leaders are responsible for clarifying and enforcing our standards of
|
42
|
+
acceptable behavior and will take appropriate and fair corrective action in
|
43
|
+
response to any behavior that they deem inappropriate, threatening, offensive,
|
44
|
+
or harmful.
|
45
|
+
|
46
|
+
Community leaders have the right and responsibility to remove, edit, or reject
|
47
|
+
comments, commits, code, wiki edits, issues, and other contributions that are
|
48
|
+
not aligned to this Code of Conduct, and will communicate reasons for moderation
|
49
|
+
decisions when appropriate.
|
50
|
+
|
51
|
+
## Scope
|
52
|
+
|
53
|
+
This Code of Conduct applies within all community spaces, and also applies when
|
54
|
+
an individual is officially representing the community in public spaces.
|
55
|
+
Examples of representing our community include using an official email address,
|
56
|
+
posting via an official social media account, or acting as an appointed
|
57
|
+
representative at an online or offline event.
|
58
|
+
|
59
|
+
## Enforcement
|
60
|
+
|
61
|
+
Instances of abusive, harassing, or otherwise unacceptable behavior may be
|
62
|
+
reported to the community leaders responsible for enforcement at
|
63
|
+
[INSERT CONTACT METHOD].
|
64
|
+
All complaints will be reviewed and investigated promptly and fairly.
|
65
|
+
|
66
|
+
All community leaders are obligated to respect the privacy and security of the
|
67
|
+
reporter of any incident.
|
68
|
+
|
69
|
+
## Enforcement Guidelines
|
70
|
+
|
71
|
+
Community leaders will follow these Community Impact Guidelines in determining
|
72
|
+
the consequences for any action they deem in violation of this Code of Conduct:
|
73
|
+
|
74
|
+
### 1. Correction
|
75
|
+
|
76
|
+
**Community Impact**: Use of inappropriate language or other behavior deemed
|
77
|
+
unprofessional or unwelcome in the community.
|
78
|
+
|
79
|
+
**Consequence**: A private, written warning from community leaders, providing
|
80
|
+
clarity around the nature of the violation and an explanation of why the
|
81
|
+
behavior was inappropriate. A public apology may be requested.
|
82
|
+
|
83
|
+
### 2. Warning
|
84
|
+
|
85
|
+
**Community Impact**: A violation through a single incident or series of
|
86
|
+
actions.
|
87
|
+
|
88
|
+
**Consequence**: A warning with consequences for continued behavior. No
|
89
|
+
interaction with the people involved, including unsolicited interaction with
|
90
|
+
those enforcing the Code of Conduct, for a specified period of time. This
|
91
|
+
includes avoiding interactions in community spaces as well as external channels
|
92
|
+
like social media. Violating these terms may lead to a temporary or permanent
|
93
|
+
ban.
|
94
|
+
|
95
|
+
### 3. Temporary Ban
|
96
|
+
|
97
|
+
**Community Impact**: A serious violation of community standards, including
|
98
|
+
sustained inappropriate behavior.
|
99
|
+
|
100
|
+
**Consequence**: A temporary ban from any sort of interaction or public
|
101
|
+
communication with the community for a specified period of time. No public or
|
102
|
+
private interaction with the people involved, including unsolicited interaction
|
103
|
+
with those enforcing the Code of Conduct, is allowed during this period.
|
104
|
+
Violating these terms may lead to a permanent ban.
|
105
|
+
|
106
|
+
### 4. Permanent Ban
|
107
|
+
|
108
|
+
**Community Impact**: Demonstrating a pattern of violation of community
|
109
|
+
standards, including sustained inappropriate behavior, harassment of an
|
110
|
+
individual, or aggression toward or disparagement of classes of individuals.
|
111
|
+
|
112
|
+
**Consequence**: A permanent ban from any sort of public interaction within the
|
113
|
+
community.
|
114
|
+
|
115
|
+
## Attribution
|
116
|
+
|
117
|
+
This Code of Conduct is adapted from the [Contributor Covenant][homepage],
|
118
|
+
version 2.1, available at
|
119
|
+
[https://www.contributor-covenant.org/version/2/1/code_of_conduct.html][v2.1].
|
120
|
+
|
121
|
+
Community Impact Guidelines were inspired by
|
122
|
+
[Mozilla's code of conduct enforcement ladder][Mozilla CoC].
|
123
|
+
|
124
|
+
For answers to common questions about this code of conduct, see the FAQ at
|
125
|
+
[https://www.contributor-covenant.org/faq][FAQ]. Translations are available at
|
126
|
+
[https://www.contributor-covenant.org/translations][translations].
|
127
|
+
|
128
|
+
[homepage]: https://www.contributor-covenant.org
|
129
|
+
[v2.1]: https://www.contributor-covenant.org/version/2/1/code_of_conduct.html
|
130
|
+
[Mozilla CoC]: https://github.com/mozilla/diversity
|
131
|
+
[FAQ]: https://www.contributor-covenant.org/faq
|
132
|
+
[translations]: https://www.contributor-covenant.org/translations
|
data/LICENSE
ADDED
@@ -0,0 +1,21 @@
|
|
1
|
+
MIT License
|
2
|
+
|
3
|
+
Copyright (c) 2025 Alexander
|
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) 2025 Alexander
|
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,241 @@
|
|
1
|
+
# Declarable
|
2
|
+
|
3
|
+
[](https://badge.fury.io/rb/declarable)
|
4
|
+
[](https://github.com/alexander-s-fokin/declarable/actions/workflows/main.yml)
|
5
|
+
|
6
|
+
Declarable is a small, powerful Ruby gem for adding declarative, reactive state management to any Ruby class. It helps you separate complex state logic from your core business logic, leading to cleaner, more maintainable, and easily testable code.
|
7
|
+
|
8
|
+
Inspired by modern frontend frameworks and patterns like CVA, Declarable brings reactive, computed properties to the Ruby backend in an elegant and intuitive way.
|
9
|
+
|
10
|
+
## Philosophy
|
11
|
+
|
12
|
+
* **Declarative:** Describe *what* state your class has, not *how* to manage it imperatively.
|
13
|
+
* **Reactive:** Derived values automatically update when their dependencies change.
|
14
|
+
* **Encapsulated:** Keep state-related logic, validations, and actions neatly organized and separated from presentation or business logic.
|
15
|
+
* **Framework-Agnostic:** Written in pure Ruby with zero external dependencies.
|
16
|
+
|
17
|
+
## Installation
|
18
|
+
|
19
|
+
Add this line to your application's Gemfile:
|
20
|
+
|
21
|
+
```ruby
|
22
|
+
gem 'declarable'
|
23
|
+
```
|
24
|
+
|
25
|
+
And then execute:
|
26
|
+
`$ bundle install`
|
27
|
+
|
28
|
+
Or install it yourself as:
|
29
|
+
`$ gem install declarable`
|
30
|
+
|
31
|
+
## Core Concepts
|
32
|
+
|
33
|
+
**Declarable** is built around three main concepts:
|
34
|
+
|
35
|
+
1. **`state`**: The raw, mutable data that your class holds. This is the "source of truth".
|
36
|
+
2. **`derive`**: Computed values that are derived from one or more states. They are reactive and automatically memoized. When a state they depend on changes, their cache is invalidated.
|
37
|
+
3. **`action`**: Encapsulated procedures that contain logic and side-effects. Actions can read states and derivations, and they can change base states, triggering the reactive system.
|
38
|
+
|
39
|
+
## Quick Start
|
40
|
+
|
41
|
+
Here's a simple example to demonstrate the basic functionality:
|
42
|
+
|
43
|
+
```ruby
|
44
|
+
require 'declarable'
|
45
|
+
|
46
|
+
class Greeter
|
47
|
+
include Declarable
|
48
|
+
|
49
|
+
# 1. Define the interface
|
50
|
+
declarable do
|
51
|
+
state :first_name, default: "John"
|
52
|
+
state :last_name, default: "Doe"
|
53
|
+
|
54
|
+
derive :full_name, from: [:first_name, :last_name] do |fname, lname|
|
55
|
+
puts "--> Deriving full_name..."
|
56
|
+
"#{fname} #{lname}"
|
57
|
+
end
|
58
|
+
end
|
59
|
+
|
60
|
+
def initialize(options = {})
|
61
|
+
# 2. Initialize the context
|
62
|
+
@context = initialize_declarable(options)
|
63
|
+
end
|
64
|
+
|
65
|
+
def greet
|
66
|
+
# 3. Use the context to access data
|
67
|
+
"Hello, #{@context.full_name}!"
|
68
|
+
end
|
69
|
+
|
70
|
+
def change_name(first_name)
|
71
|
+
@context.first_name = first_name
|
72
|
+
end
|
73
|
+
end
|
74
|
+
|
75
|
+
# --- Usage ---
|
76
|
+
greeter = Greeter.new(first_name: "Jane")
|
77
|
+
|
78
|
+
puts greeter.greet
|
79
|
+
# --> Deriving full_name...
|
80
|
+
# => "Hello, Jane Doe!"
|
81
|
+
|
82
|
+
puts greeter.greet
|
83
|
+
# => "Hello, Jane Doe!" (No console output, result is memoized)
|
84
|
+
|
85
|
+
greeter.change_name("John")
|
86
|
+
# The cache for :full_name is now invalidated.
|
87
|
+
|
88
|
+
puts greeter.greet
|
89
|
+
# --> Deriving full_name...
|
90
|
+
# => "Hello, John Doe!"
|
91
|
+
```
|
92
|
+
|
93
|
+
## DSL Reference
|
94
|
+
|
95
|
+
### `state`
|
96
|
+
|
97
|
+
Defines a base, mutable state.
|
98
|
+
|
99
|
+
```ruby
|
100
|
+
declarable do
|
101
|
+
# With a default value
|
102
|
+
state :status, default: "pending"
|
103
|
+
|
104
|
+
# With validations
|
105
|
+
state :role, default: "user", validates: {
|
106
|
+
inclusion: { in: %w[user admin editor] }
|
107
|
+
}
|
108
|
+
|
109
|
+
state :email, validates: { presence: true }
|
110
|
+
end
|
111
|
+
```
|
112
|
+
|
113
|
+
### `derive`
|
114
|
+
|
115
|
+
Defines a computed, reactive value.
|
116
|
+
|
117
|
+
#### With a Block
|
118
|
+
|
119
|
+
For most use cases, a block is the simplest way to define a derivation. The block arguments correspond to the values of the dependencies listed in `from`.
|
120
|
+
|
121
|
+
```ruby
|
122
|
+
declarable do
|
123
|
+
state :price, default: 100
|
124
|
+
state :tax_rate, default: 0.2
|
125
|
+
|
126
|
+
derive :total_price, from: [:price, :tax_rate] do |price, tax|
|
127
|
+
price * (1 + tax)
|
128
|
+
end
|
129
|
+
end
|
130
|
+
```
|
131
|
+
|
132
|
+
#### With a Class
|
133
|
+
|
134
|
+
For complex, reusable logic, you can specify a transformer class. The class must respond to `.call(dependencies_hash)`.
|
135
|
+
|
136
|
+
```ruby
|
137
|
+
class MyComplexTransformer
|
138
|
+
def self.call(price:, tax_rate:)
|
139
|
+
# ... complex logic
|
140
|
+
end
|
141
|
+
end
|
142
|
+
|
143
|
+
declarable do
|
144
|
+
# ... states
|
145
|
+
derive :total_price, from: [:price, :tax_rate], class: MyComplexTransformer
|
146
|
+
end
|
147
|
+
```
|
148
|
+
|
149
|
+
### `action`
|
150
|
+
|
151
|
+
Defines an encapsulated procedure. The block receives the context object as its first argument, followed by any arguments passed to `.call`.
|
152
|
+
|
153
|
+
```ruby
|
154
|
+
declarable do
|
155
|
+
state :page, default: 1
|
156
|
+
|
157
|
+
action :next_page do |context|
|
158
|
+
context.page += 1
|
159
|
+
end
|
160
|
+
|
161
|
+
action :set_page do |context, new_page_number|
|
162
|
+
context.page = new_page_number
|
163
|
+
end
|
164
|
+
end
|
165
|
+
|
166
|
+
# Usage:
|
167
|
+
# @context.next_page.call
|
168
|
+
# @context.set_page.call(5)
|
169
|
+
```
|
170
|
+
|
171
|
+
## Advanced Example
|
172
|
+
|
173
|
+
This example demonstrates how all parts work together to create a simple search component's logic.
|
174
|
+
|
175
|
+
```ruby
|
176
|
+
require 'declarable'
|
177
|
+
|
178
|
+
# A dummy class to represent our search logic
|
179
|
+
class MockSearchService
|
180
|
+
def self.call(query)
|
181
|
+
query.to_s.empty? ? [] : ["Result for '#{query}' 1", "Result for '#{query}' 2"]
|
182
|
+
end
|
183
|
+
end
|
184
|
+
|
185
|
+
class SearchComponent
|
186
|
+
include Declarable
|
187
|
+
|
188
|
+
declarable do
|
189
|
+
# 1. STATES
|
190
|
+
state :query, default: ""
|
191
|
+
state :results, default: []
|
192
|
+
|
193
|
+
# 2. DERIVATIONS
|
194
|
+
derive :found_count, from: :results, do: ->(res) { res.size }
|
195
|
+
|
196
|
+
derive :status_message, from: [:query, :found_count] do |q, count|
|
197
|
+
q.empty? ? "Enter a query to search." : "Found #{count} results."
|
198
|
+
end
|
199
|
+
|
200
|
+
# 3. ACTION
|
201
|
+
action :perform_search do |context|
|
202
|
+
# Actions can read state and call external services
|
203
|
+
found_data = MockSearchService.call(context.query)
|
204
|
+
# Actions can change state, triggering the reactive system
|
205
|
+
context.results = found_data
|
206
|
+
end
|
207
|
+
end
|
208
|
+
|
209
|
+
def initialize
|
210
|
+
@context = initialize_declarable
|
211
|
+
end
|
212
|
+
|
213
|
+
# Expose the context for interaction
|
214
|
+
attr_reader :context
|
215
|
+
end
|
216
|
+
|
217
|
+
# --- Usage ---
|
218
|
+
search = SearchComponent.new
|
219
|
+
|
220
|
+
puts search.context.status_message
|
221
|
+
# => "Enter a query to search."
|
222
|
+
|
223
|
+
search.context.query = "Ruby Gems"
|
224
|
+
puts search.context.status_message # `found_count` is 0 because `results` is still []
|
225
|
+
# => "Found 0 results."
|
226
|
+
|
227
|
+
# Call the action to perform the search
|
228
|
+
search.context.perform_search.call
|
229
|
+
|
230
|
+
# Now `results` is updated, and `found_count` and `status_message` are re-derived!
|
231
|
+
puts search.context.status_message
|
232
|
+
# => "Found 2 results."
|
233
|
+
```
|
234
|
+
|
235
|
+
## Contributing
|
236
|
+
|
237
|
+
Bug reports and pull requests are welcome on GitHub at [https://github.com/alexander-s-fokin/declarable](https://github.com/alexander-s-fokin/declarable).
|
238
|
+
|
239
|
+
## License
|
240
|
+
|
241
|
+
The gem is available as open source under the terms of the [MIT License](https://opensource.org/licenses/MIT).
|
data/Rakefile
ADDED
@@ -0,0 +1,86 @@
|
|
1
|
+
# frozen_string_literal: true
|
2
|
+
|
3
|
+
require_relative "action"
|
4
|
+
|
5
|
+
module Declarable
|
6
|
+
class Context
|
7
|
+
def initialize(definition, initial_values = {})
|
8
|
+
@definition = definition
|
9
|
+
@data = {}
|
10
|
+
@memoized_derivations = {}
|
11
|
+
|
12
|
+
@definition.states.each do |name, config|
|
13
|
+
value = initial_values.fetch(name, config[:default])
|
14
|
+
Validator.validate!(name, value, config[:validations]) if config[:validations]
|
15
|
+
@data[name] = value
|
16
|
+
end
|
17
|
+
end
|
18
|
+
|
19
|
+
def method_missing(method_name, *args, &block)
|
20
|
+
if method_name.end_with?("=")
|
21
|
+
state_name = method_name.to_s.chomp("=").to_sym
|
22
|
+
return super unless @data.key?(state_name) # Разрешаем менять только базовые `state`
|
23
|
+
|
24
|
+
set_state(state_name, args.first)
|
25
|
+
else
|
26
|
+
value = get_value(method_name)
|
27
|
+
return value unless value.nil?
|
28
|
+
|
29
|
+
if @definition.actions.key?(method_name)
|
30
|
+
action_block = @definition.actions[method_name]
|
31
|
+
return Action.new(self, action_block)
|
32
|
+
end
|
33
|
+
|
34
|
+
super
|
35
|
+
end
|
36
|
+
end
|
37
|
+
|
38
|
+
def respond_to_missing?(method_name, include_private = false)
|
39
|
+
name = method_name.to_s.chomp("=").to_sym
|
40
|
+
@data.key?(name) || @definition.derivations.key?(name) || @definition.actions.key?(name) || super
|
41
|
+
end
|
42
|
+
|
43
|
+
private
|
44
|
+
|
45
|
+
def get_value(name)
|
46
|
+
return @data[name] if @data.key?(name)
|
47
|
+
return @memoized_derivations[name] if @memoized_derivations.key?(name)
|
48
|
+
|
49
|
+
if @definition.derivations.key?(name)
|
50
|
+
return execute_derivation(name)
|
51
|
+
end
|
52
|
+
|
53
|
+
nil
|
54
|
+
end
|
55
|
+
|
56
|
+
def set_state(name, value)
|
57
|
+
state_config = @definition.states[name]
|
58
|
+
# Вызываем валидатор перед изменением значения
|
59
|
+
Validator.validate!(name, value, state_config[:validations]) if state_config[:validations]
|
60
|
+
|
61
|
+
return if @data[name] == value
|
62
|
+
|
63
|
+
@data[name] = value
|
64
|
+
invalidate_cache_for(name)
|
65
|
+
end
|
66
|
+
|
67
|
+
def invalidate_cache_for(state_name)
|
68
|
+
dependents = @definition.dependency_graph[state_name]
|
69
|
+
return unless dependents
|
70
|
+
|
71
|
+
dependents.each do |dependent_name|
|
72
|
+
if @memoized_derivations.delete(dependent_name)
|
73
|
+
invalidate_cache_for(dependent_name)
|
74
|
+
end
|
75
|
+
end
|
76
|
+
end
|
77
|
+
|
78
|
+
def execute_derivation(name)
|
79
|
+
derivation = @definition.derivations[name]
|
80
|
+
|
81
|
+
dependency_values = derivation[:dependencies].map { |dep| get_value(dep) }
|
82
|
+
|
83
|
+
@memoized_derivations[name] = derivation[:block].call(*dependency_values)
|
84
|
+
end
|
85
|
+
end
|
86
|
+
end
|
@@ -0,0 +1,40 @@
|
|
1
|
+
# frozen_string_literal: true
|
2
|
+
|
3
|
+
module Declarable
|
4
|
+
class Definition
|
5
|
+
attr_reader :states, :derivations, :dependency_graph, :actions
|
6
|
+
|
7
|
+
def initialize
|
8
|
+
@states = {}
|
9
|
+
@derivations = {}
|
10
|
+
# dependency_graph: { state_a: [:derivation_x, :derivation_y] }
|
11
|
+
@dependency_graph = Hash.new { |h, k| h[k] = [] }
|
12
|
+
@actions = {}
|
13
|
+
end
|
14
|
+
|
15
|
+
def state(name, default: nil, validates: {})
|
16
|
+
@states[name.to_sym] = {
|
17
|
+
default: default,
|
18
|
+
validations: validates
|
19
|
+
}
|
20
|
+
end
|
21
|
+
|
22
|
+
def derive(name, from:, &block)
|
23
|
+
dependencies = Array(from)
|
24
|
+
derivation_name = name.to_sym
|
25
|
+
|
26
|
+
@derivations[derivation_name] = {
|
27
|
+
dependencies: dependencies,
|
28
|
+
block: block
|
29
|
+
}
|
30
|
+
|
31
|
+
dependencies.each do |dep|
|
32
|
+
@dependency_graph[dep] << derivation_name
|
33
|
+
end
|
34
|
+
end
|
35
|
+
|
36
|
+
def action(name, &block)
|
37
|
+
@actions[name.to_sym] = block
|
38
|
+
end
|
39
|
+
end
|
40
|
+
end
|
@@ -0,0 +1,43 @@
|
|
1
|
+
# frozen_string_literal: true
|
2
|
+
|
3
|
+
# lib/declarable/validator.rb
|
4
|
+
require_relative "validation_error"
|
5
|
+
|
6
|
+
module Declarable
|
7
|
+
module Validator
|
8
|
+
# Главный метод, который принимает имя, значение и хэш правил.
|
9
|
+
def self.validate!(state_name, value, rules)
|
10
|
+
rules.each do |rule_name, options|
|
11
|
+
validator_method = "validate_#{rule_name}!"
|
12
|
+
unless respond_to?(validator_method, true)
|
13
|
+
raise "Unknown validator: #{rule_name}"
|
14
|
+
end
|
15
|
+
|
16
|
+
# Вызываем конкретный метод валидации
|
17
|
+
public_send(validator_method, state_name, value, options)
|
18
|
+
end
|
19
|
+
end
|
20
|
+
|
21
|
+
private
|
22
|
+
|
23
|
+
# --- Наши конкретные валидаторы ---
|
24
|
+
|
25
|
+
# Проверяет наличие значения
|
26
|
+
def self.validate_presence!(state_name, value, options)
|
27
|
+
is_blank = value.nil? || (value.respond_to?(:empty?) && value.empty?)
|
28
|
+
if is_blank
|
29
|
+
message = options.is_a?(Hash) ? options[:message] : "can't be blank"
|
30
|
+
raise ValidationError, "`#{state_name}` #{message}"
|
31
|
+
end
|
32
|
+
end
|
33
|
+
|
34
|
+
# Проверяет вхождение в коллекцию
|
35
|
+
def self.validate_inclusion!(state_name, value, options)
|
36
|
+
collection = options[:in]
|
37
|
+
unless collection.include?(value)
|
38
|
+
message = options.fetch(:message, "is not in the list: #{collection.join(', ')}")
|
39
|
+
raise ValidationError, "`#{state_name}`: value `#{value}` #{message}"
|
40
|
+
end
|
41
|
+
end
|
42
|
+
end
|
43
|
+
end
|
data/lib/declarable.rb
ADDED
@@ -0,0 +1,40 @@
|
|
1
|
+
# frozen_string_literal: true
|
2
|
+
|
3
|
+
require_relative "declarable/version"
|
4
|
+
require_relative "declarable/validation_error"
|
5
|
+
require_relative "declarable/validator"
|
6
|
+
require_relative "declarable/action"
|
7
|
+
require_relative "declarable/definition"
|
8
|
+
require_relative "declarable/context"
|
9
|
+
|
10
|
+
module Declarable
|
11
|
+
def self.included(base)
|
12
|
+
base.extend(ClassMethods)
|
13
|
+
base.instance_variable_set(:@declarable_definition, nil)
|
14
|
+
|
15
|
+
# Создаем методы для работы с class-level переменной
|
16
|
+
base.define_singleton_method(:declarable_definition) do
|
17
|
+
@declarable_definition
|
18
|
+
end
|
19
|
+
|
20
|
+
base.define_singleton_method(:declarable_definition=) do |value|
|
21
|
+
@declarable_definition = value
|
22
|
+
end
|
23
|
+
end
|
24
|
+
|
25
|
+
module ClassMethods
|
26
|
+
# Наш главный DSL-метод
|
27
|
+
def declarable(&block)
|
28
|
+
self.declarable_definition = Definition.new
|
29
|
+
self.declarable_definition.instance_eval(&block)
|
30
|
+
end
|
31
|
+
end
|
32
|
+
|
33
|
+
private
|
34
|
+
|
35
|
+
# Инициализатор, который будет вызываться в компоненте
|
36
|
+
def initialize_declarable(options = {})
|
37
|
+
# Создаем runtime-контекст, передавая ему описание и начальные значения
|
38
|
+
@context = Context.new(self.class.declarable_definition, options)
|
39
|
+
end
|
40
|
+
end
|
data/sig/declarable.rbs
ADDED
metadata
ADDED
@@ -0,0 +1,79 @@
|
|
1
|
+
--- !ruby/object:Gem::Specification
|
2
|
+
name: declarable
|
3
|
+
version: !ruby/object:Gem::Version
|
4
|
+
version: 0.1.0
|
5
|
+
platform: ruby
|
6
|
+
authors:
|
7
|
+
- Alexander Fokin
|
8
|
+
autorequire:
|
9
|
+
bindir: exe
|
10
|
+
cert_chain: []
|
11
|
+
date: 2025-08-11 00:00:00.000000000 Z
|
12
|
+
dependencies:
|
13
|
+
- !ruby/object:Gem::Dependency
|
14
|
+
name: rspec
|
15
|
+
requirement: !ruby/object:Gem::Requirement
|
16
|
+
requirements:
|
17
|
+
- - "~>"
|
18
|
+
- !ruby/object:Gem::Version
|
19
|
+
version: '3.0'
|
20
|
+
type: :development
|
21
|
+
prerelease: false
|
22
|
+
version_requirements: !ruby/object:Gem::Requirement
|
23
|
+
requirements:
|
24
|
+
- - "~>"
|
25
|
+
- !ruby/object:Gem::Version
|
26
|
+
version: '3.0'
|
27
|
+
description: Declarable provides a DSL to define states, derived values, and actions.
|
28
|
+
It helps separate state management from business logic, creating cleaner, more maintainable,
|
29
|
+
and easily testable classes.
|
30
|
+
email:
|
31
|
+
- alexander.s.fokin@gmail.com
|
32
|
+
executables: []
|
33
|
+
extensions: []
|
34
|
+
extra_rdoc_files: []
|
35
|
+
files:
|
36
|
+
- ".rubocop.yml"
|
37
|
+
- CHANGELOG.md
|
38
|
+
- CODE_OF_CONDUCT.md
|
39
|
+
- LICENSE
|
40
|
+
- LICENSE.txt
|
41
|
+
- README.md
|
42
|
+
- Rakefile
|
43
|
+
- lib/declarable.rb
|
44
|
+
- lib/declarable/action.rb
|
45
|
+
- lib/declarable/context.rb
|
46
|
+
- lib/declarable/definition.rb
|
47
|
+
- lib/declarable/validation_error.rb
|
48
|
+
- lib/declarable/validator.rb
|
49
|
+
- lib/declarable/version.rb
|
50
|
+
- sig/declarable.rbs
|
51
|
+
homepage: https://github.com/alexander-s-fokin/declarable
|
52
|
+
licenses:
|
53
|
+
- MIT
|
54
|
+
metadata:
|
55
|
+
homepage_uri: https://github.com/alexander-s-fokin/declarable
|
56
|
+
source_code_uri: https://github.com/alexander-s-fokin/declarable
|
57
|
+
changelog_uri: https://github.com/alexander-s-fokin/declarable/blob/main/CHANGELOG.md
|
58
|
+
allowed_push_host: https://rubygems.org
|
59
|
+
post_install_message:
|
60
|
+
rdoc_options: []
|
61
|
+
require_paths:
|
62
|
+
- lib
|
63
|
+
required_ruby_version: !ruby/object:Gem::Requirement
|
64
|
+
requirements:
|
65
|
+
- - ">="
|
66
|
+
- !ruby/object:Gem::Version
|
67
|
+
version: 3.1.0
|
68
|
+
required_rubygems_version: !ruby/object:Gem::Requirement
|
69
|
+
requirements:
|
70
|
+
- - ">="
|
71
|
+
- !ruby/object:Gem::Version
|
72
|
+
version: '0'
|
73
|
+
requirements: []
|
74
|
+
rubygems_version: 3.5.22
|
75
|
+
signing_key:
|
76
|
+
specification_version: 4
|
77
|
+
summary: A simple, powerful library for declarative, reactive state management in
|
78
|
+
any Ruby class.
|
79
|
+
test_files: []
|