gyros 0.1.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: 1d58f45e9b1311b52befffe94c4add6b6d5efbb735b1ea4ac898469db71aa19e
4
+ data.tar.gz: ff88e0f8a6009b2f789eb50807746fdab0a38376598d0958814f91cb8c8d5bda
5
+ SHA512:
6
+ metadata.gz: 9d0750540abaa0bd057f61e0a38b032d1f6d8c5196460baf2df7d0480f125a98c4bb7bbc5eee8fd303bfd46a8dcc7075fde005c8aa33e723c56ee9cb25ebef56
7
+ data.tar.gz: 2ccb83d6f5101a8991a0755a672a0c217840449bdfef6baebbc9a0db3f72cfcc58ad68b09113f74e6d48bfc60f452a7b54ad77cb312de87e02f1fb381d7b0bcb
data/.rspec ADDED
@@ -0,0 +1,3 @@
1
+ --format documentation
2
+ --color
3
+ --require spec_helper
data/.rubocop.yml ADDED
@@ -0,0 +1,16 @@
1
+ # This is the configuration used to check the rubocop source code.
2
+
3
+ inherit_from:
4
+ - https://raw.githubusercontent.com/serverscom/best-practices/rubocop-0.88/.rubocop.yml
5
+ - .rubocop_todo.yml
6
+
7
+ inherit_mode:
8
+ merge:
9
+ - Exclude
10
+
11
+ require:
12
+ - rubocop-performance
13
+
14
+ AllCops:
15
+ TargetRubyVersion: 3.0
16
+ NewCops: enable
data/.rubocop_todo.yml ADDED
@@ -0,0 +1,16 @@
1
+ # This configuration was generated by
2
+ # `rubocop --auto-gen-config`
3
+ # on 2023-05-19 12:34:19 UTC using RuboCop version 1.48.0.
4
+ # The point is for the user to remove these configuration records
5
+ # one by one as the offenses are removed from the code base.
6
+ # Note that changes in the inspected code, or installation of new
7
+ # versions of RuboCop, may require this file to be generated again.
8
+
9
+ # Offense count: 10
10
+ # This cop supports safe autocorrection (--autocorrect).
11
+ # Configuration parameters: EnforcedStyle, ConsistentQuotesInMultiline.
12
+ # SupportedStyles: single_quotes, double_quotes
13
+ Style/StringLiterals:
14
+ Exclude:
15
+ - 'Gemfile'
16
+ - 'Rakefile'
@@ -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 kirik910@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,16 @@
1
+ # frozen_string_literal: true
2
+
3
+ source "https://rubygems.org"
4
+
5
+ # Specify your gem's dependencies in gyros.gemspec
6
+ gemspec
7
+
8
+ gem 'activesupport'
9
+ gem 'pry'
10
+ gem "rake", "~> 13.0"
11
+
12
+ gem "rspec", "~> 3.0"
13
+
14
+ gem 'racc'
15
+ gem "rubocop", "~> 1.21"
16
+ gem 'rubocop-performance'
data/Gemfile.lock ADDED
@@ -0,0 +1,102 @@
1
+ PATH
2
+ remote: .
3
+ specs:
4
+ gyros (0.1.4)
5
+
6
+ GEM
7
+ remote: https://rubygems.org/
8
+ specs:
9
+ activesupport (8.0.2)
10
+ base64
11
+ benchmark (>= 0.3)
12
+ bigdecimal
13
+ concurrent-ruby (~> 1.0, >= 1.3.1)
14
+ connection_pool (>= 2.2.5)
15
+ drb
16
+ i18n (>= 1.6, < 2)
17
+ logger (>= 1.4.2)
18
+ minitest (>= 5.1)
19
+ securerandom (>= 0.3)
20
+ tzinfo (~> 2.0, >= 2.0.5)
21
+ uri (>= 0.13.1)
22
+ ast (2.4.2)
23
+ base64 (0.2.0)
24
+ benchmark (0.4.0)
25
+ bigdecimal (3.1.9)
26
+ coderay (1.1.3)
27
+ concurrent-ruby (1.3.5)
28
+ connection_pool (2.5.2)
29
+ diff-lcs (1.5.0)
30
+ drb (2.2.1)
31
+ i18n (1.14.7)
32
+ concurrent-ruby (~> 1.0)
33
+ json (2.6.1)
34
+ logger (1.7.0)
35
+ method_source (1.0.0)
36
+ minitest (5.25.5)
37
+ parallel (1.22.1)
38
+ parser (3.2.1.1)
39
+ ast (~> 2.4.1)
40
+ pry (0.14.2)
41
+ coderay (~> 1.1)
42
+ method_source (~> 1.0)
43
+ racc (1.8.1)
44
+ rainbow (3.0.0)
45
+ rake (13.0.6)
46
+ regexp_parser (2.7.0)
47
+ rexml (3.2.5)
48
+ rspec (3.12.0)
49
+ rspec-core (~> 3.12.0)
50
+ rspec-expectations (~> 3.12.0)
51
+ rspec-mocks (~> 3.12.0)
52
+ rspec-core (3.12.1)
53
+ rspec-support (~> 3.12.0)
54
+ rspec-expectations (3.12.2)
55
+ diff-lcs (>= 1.2.0, < 2.0)
56
+ rspec-support (~> 3.12.0)
57
+ rspec-mocks (3.12.3)
58
+ diff-lcs (>= 1.2.0, < 2.0)
59
+ rspec-support (~> 3.12.0)
60
+ rspec-support (3.12.0)
61
+ rubocop (1.48.0)
62
+ json (~> 2.3)
63
+ parallel (~> 1.10)
64
+ parser (>= 3.2.0.0)
65
+ rainbow (>= 2.2.2, < 4.0)
66
+ regexp_parser (>= 1.8, < 3.0)
67
+ rexml (>= 3.2.5, < 4.0)
68
+ rubocop-ast (>= 1.26.0, < 2.0)
69
+ ruby-progressbar (~> 1.7)
70
+ unicode-display_width (>= 2.4.0, < 3.0)
71
+ rubocop-ast (1.27.0)
72
+ parser (>= 3.2.1.0)
73
+ rubocop-performance (1.17.1)
74
+ rubocop (>= 1.7.0, < 2.0)
75
+ rubocop-ast (>= 0.4.0)
76
+ ruby-progressbar (1.13.0)
77
+ securerandom (0.4.1)
78
+ tzinfo (2.0.6)
79
+ concurrent-ruby (~> 1.0)
80
+ unicode-display_width (2.4.2)
81
+ uri (1.0.3)
82
+
83
+ PLATFORMS
84
+ arm64-darwin
85
+ arm64-darwin-22
86
+ arm64-darwin-23
87
+ ruby
88
+ x86_64-darwin
89
+ x86_64-linux
90
+
91
+ DEPENDENCIES
92
+ activesupport
93
+ gyros!
94
+ pry
95
+ racc
96
+ rake (~> 13.0)
97
+ rspec (~> 3.0)
98
+ rubocop (~> 1.21)
99
+ rubocop-performance
100
+
101
+ BUNDLED WITH
102
+ 2.4.2
data/LICENSE.txt ADDED
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2023 Kirill Zaitsev
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,209 @@
1
+ # Gyros
2
+
3
+ Gyros is a powerful Ruby library designed to simplify data handling and querying. It provides a flexible and intuitive way to build complex queries dynamically while keeping your code clean and maintainable.
4
+
5
+ ## Installation
6
+
7
+ Add this line to your application's Gemfile:
8
+
9
+ ```ruby
10
+ gem 'gyros'
11
+ ```
12
+
13
+ And then execute:
14
+
15
+ ```bash
16
+ bundle install
17
+ ```
18
+
19
+ Or install it yourself as:
20
+
21
+ ```bash
22
+ gem install gyros
23
+ ```
24
+
25
+ ## Features
26
+
27
+ ### Collection Management
28
+ - **Multiple Collections**: Define multiple collections within a single repository for different query contexts
29
+ - **Context Awareness**: Pass context data to your queries that can be used by filters and modifiers
30
+ - **Deep Cloning**: Collections are safely cloned when modified, preventing unintended side effects
31
+
32
+ ### Scoping System
33
+ - **Default Scopes**: Define base conditions that apply to all queries in a collection
34
+ - **Action Scopes**: Create specific scopes for different actions (list, show, etc.)
35
+ - **Parameterized Scopes**: Scopes can accept parameters for dynamic behavior
36
+
37
+ ### Filtering System
38
+
39
+ #### Basic Filters
40
+ Simple single or multi-parameter filters for exact matching:
41
+
42
+ ```ruby
43
+ filter :name do |name|
44
+ where(name: name)
45
+ end
46
+
47
+ filter :role, :active do |role, active|
48
+ where(role: role, active: active)
49
+ end
50
+ ```
51
+
52
+ #### Nested Filters
53
+ Group related filters under a namespace for better organization:
54
+
55
+ ```ruby
56
+ nested_filter :created_at do
57
+ filter :from do |date|
58
+ where('created_at >= ?', date)
59
+ end
60
+
61
+ filter :to do |date|
62
+ where('created_at <= ?', date)
63
+ end
64
+ end
65
+ ```
66
+
67
+ #### Any-of Filters
68
+ Match any of multiple conditions for flexible searching:
69
+
70
+ ```ruby
71
+ any_of_filter :search_by, :email, :phone do |params|
72
+ result = []
73
+ result.concat(where('email LIKE ?', "%#{params[:email]}%")) if params[:email]
74
+ result.concat(where('phone LIKE ?', "%#{params[:phone]}%")) if params[:phone]
75
+ result.uniq
76
+ end
77
+ ```
78
+
79
+ ### Sorting System
80
+ - **Field-based Sorting**: Define sortable fields with custom logic
81
+ - **Direction Control**: Support for ascending and descending order
82
+ - **Context-aware Sorting**: Implement complex sorting logic using context
83
+
84
+ ```ruby
85
+ order_by :relevance do |field, direction, context:|
86
+ next self unless context[:query]
87
+
88
+ order_by_relevance(context[:query])
89
+ end
90
+ ```
91
+
92
+ ### Modifiers System
93
+ Modifiers provide a way to customize queries with chainable methods:
94
+
95
+ - **Basic Modifiers**: Simple query modifications
96
+ - **Context-aware Modifiers**: Access context in modifiers
97
+ - **Final Modifiers**: Prevent further modifications after application
98
+ - **Frozen State Handling**: Safe handling of frozen collections
99
+
100
+ ```ruby
101
+ modifier :visible_for do |user|
102
+ if user.admin?
103
+ self
104
+ else
105
+ where.not(role: 'admin')
106
+ end
107
+ end
108
+
109
+ modifier :only_department, final: true do |department|
110
+ where(department: department)
111
+ end
112
+ ```
113
+
114
+ ## Usage Example
115
+
116
+ First, define your base repository:
117
+
118
+ ```ruby
119
+ class BaseRepository < Gyros::Base
120
+ def list(params = {})
121
+ apply_with_scope(:list, params)
122
+ end
123
+
124
+ def show(id, params = {})
125
+ apply_with_scope(:show, params).find(id)
126
+ end
127
+ end
128
+ ```
129
+
130
+ Then create your specific repository:
131
+
132
+ ```ruby
133
+ class UserRepository < BaseRepository
134
+ model { User.all }
135
+
136
+ collection :default do
137
+ # Default scope for all queries
138
+ default_scope do
139
+ where(deleted_at: nil)
140
+ end
141
+
142
+ # Modifiers
143
+ modifier :visible_for do |user|
144
+ if user.admin?
145
+ self
146
+ else
147
+ where.not(role: 'admin')
148
+ end
149
+ end
150
+
151
+ # Scopes
152
+ scope_for(:list) do
153
+ where(active: true)
154
+ end
155
+
156
+ # Sorting
157
+ order_by :name, :email, :created_at do |field, direction|
158
+ order(field => direction)
159
+ end
160
+
161
+ # Basic filters
162
+ filter :role do |role|
163
+ where(role: role)
164
+ end
165
+
166
+ # Nested filters
167
+ nested_filter :date_range do
168
+ filter :from do |date|
169
+ where('created_at >= ?', date)
170
+ end
171
+
172
+ filter :to do |date|
173
+ where('created_at <= ?', date)
174
+ end
175
+ end
176
+
177
+ # Any-of filters
178
+ any_of_filter :search do |params|
179
+ next self if params.empty?
180
+
181
+ result = []
182
+ result.concat(where('email LIKE ?', "%#{params[:email]}%")) if params[:email]
183
+ result.concat(where('name LIKE ?', "%#{params[:name]}%")) if params[:name]
184
+ result.uniq
185
+ end
186
+ end
187
+ end
188
+ ```
189
+
190
+ Use your repository:
191
+
192
+ ```ruby
193
+ repository = UserRepository.new(:default)
194
+ .visible_for(current_user)
195
+ .with_context(query: 'search term')
196
+
197
+ # Apply filters, sorting and scopes
198
+ users = repository.list(
199
+ role: 'manager',
200
+ date_range: { from: 1.month.ago, to: Time.now },
201
+ search: { email: '@company.com' },
202
+ sort: 'created_at',
203
+ dir: :desc
204
+ )
205
+ ```
206
+
207
+ ## License
208
+
209
+ 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,12 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "bundler/gem_tasks"
4
+ require "rspec/core/rake_task"
5
+
6
+ RSpec::Core::RakeTask.new(:spec)
7
+
8
+ require "rubocop/rake_task"
9
+
10
+ RuboCop::RakeTask.new
11
+
12
+ task default: %i[spec rubocop]
data/lib/gyros/base.rb ADDED
@@ -0,0 +1,69 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Gyros
4
+ class Base
5
+ def initialize(collection_name)
6
+ @finalized = false
7
+ @finalized_by = nil
8
+
9
+ @collection = self.class.collections.fetch(collection_name).new(self.class.model)
10
+ end
11
+
12
+ def apply_with_scope(scope, params)
13
+ @collection.apply_with_scope(scope, params)
14
+ end
15
+
16
+ def scope_for(method)
17
+ @collection.scope_for(method)
18
+ end
19
+
20
+ def respond_to_missing?(meth, *args)
21
+ @collection.respond_to?(meth) || super
22
+ end
23
+
24
+ def method_missing(meth, *args, **kwargs, &block)
25
+ if @collection.respond_to?(meth) && @collection.class.modifiers.include?(meth)
26
+ copy = deep_dup
27
+ copy.instance_variable_set(
28
+ :@collection,
29
+ @collection.deep_dup.public_send(meth, *args, **kwargs, &block)
30
+ )
31
+ copy
32
+ else
33
+ super
34
+ end
35
+ end
36
+
37
+ def context
38
+ @collection.context
39
+ end
40
+
41
+ def with_context(context)
42
+ @collection.with_context(context)
43
+ end
44
+
45
+ class << self
46
+ def model(value = nil, &block)
47
+ if value
48
+ @model = value
49
+ elsif block
50
+ @model = block
51
+ elsif @model.is_a?(Proc)
52
+ @model.call
53
+ else
54
+ @model
55
+ end
56
+ end
57
+
58
+ def collections
59
+ @collections ||= {}
60
+ end
61
+
62
+ def collection(name, &block)
63
+ collections[name.to_sym] ||= Class.new(Gyros::Collection)
64
+ collections[name.to_sym].instance_eval(&block) if block_given?
65
+ collections[name.to_sym]
66
+ end
67
+ end
68
+ end
69
+ end
@@ -0,0 +1,33 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Gyros
4
+ class Collection
5
+ include Gyros::Features::Common
6
+ include Gyros::Features::Modifiable
7
+ include Gyros::Features::Scopeable
8
+ include Gyros::Features::Filterable
9
+ include Gyros::Features::Sortable
10
+
11
+ def initialize(base_scope)
12
+ @base_scope = base_scope
13
+ end
14
+
15
+ def context
16
+ @context ||= {}
17
+ end
18
+
19
+ def with_context(ctx)
20
+ @context = ctx
21
+
22
+ self
23
+ end
24
+
25
+ def apply_with_scope(scope, params)
26
+ apply(scope_for(scope), params)
27
+ end
28
+
29
+ def apply(scope, params)
30
+ super(scope, params, context: context)
31
+ end
32
+ end
33
+ end
@@ -0,0 +1,22 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Gyros
4
+ module Features
5
+ module Common
6
+ def self.included(child)
7
+ child.send(:include, InstanceMethods)
8
+
9
+ super
10
+ end
11
+
12
+ module InstanceMethods
13
+ # Applies defined filters to scope.
14
+ # Only applies a filter if params hash has
15
+ # all of the keys defined by filter.
16
+ def apply(scope, _params, **kwargs)
17
+ scope
18
+ end
19
+ end
20
+ end
21
+ end
22
+ end
@@ -0,0 +1,57 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Gyros
4
+ module Features
5
+ module Filterable
6
+ def self.included(child)
7
+ child.send(:extend, ClassMethods)
8
+ child.send(:include, InstanceMethods)
9
+
10
+ super
11
+ end
12
+
13
+ module InstanceMethods
14
+ # Applies defined filters to scope.
15
+ # Only applies a filter if params hash has
16
+ # all of the keys defined by filter.
17
+ def apply(scope, params, **kwargs)
18
+ result = scope
19
+
20
+ self.class.filters.each do |filter|
21
+ next unless filter.match?(params)
22
+
23
+ result = filter.apply(result, params, **kwargs)
24
+ end
25
+
26
+ super(result, params, **kwargs)
27
+ end
28
+ end
29
+
30
+ module ClassMethods
31
+ def filters
32
+ @filters ||= []
33
+ end
34
+
35
+ def filters=(v)
36
+ @filters = v
37
+ end
38
+
39
+ def respond_to_missing?(meth, *args)
40
+ Gyros::Registry.filters.key?(meth) || super
41
+ end
42
+
43
+ def method_missing(meth, *args, &block)
44
+ if Gyros::Registry.filters[meth]
45
+ define_singleton_method(meth) do |*args, &block|
46
+ self.filters += Array(Gyros::Registry.filters[meth].call(*args, &block))
47
+ end
48
+
49
+ send(meth, *args, &block)
50
+ else
51
+ super
52
+ end
53
+ end
54
+ end
55
+ end
56
+ end
57
+ end
@@ -0,0 +1,55 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Gyros
4
+ module Features
5
+ module Modifiable
6
+ def self.included(child)
7
+ child.send(:extend, ClassMethods)
8
+
9
+ super
10
+ end
11
+
12
+ def initialize(*args)
13
+ @finalized = false
14
+ @finalized_by = nil
15
+
16
+ super
17
+ end
18
+
19
+ def freeze
20
+ super
21
+
22
+ self
23
+ end
24
+
25
+ module ClassMethods
26
+ def modifiers
27
+ @modifiers ||= Set.new
28
+ end
29
+
30
+ def modifier(method, final: false, &block)
31
+ modifiers << method
32
+
33
+ define_method(method) do |*args, **kwargs|
34
+ if @finalized
35
+ raise "No more modifiers can be applied, finalized by: #{@finalized_by}"
36
+ elsif frozen?
37
+ deep_dup.send(method, *args)
38
+ else
39
+ if final
40
+ @finalized = true
41
+ @finalized_by = method
42
+ end
43
+
44
+ @base_scope = @base_scope
45
+ .deep_dup
46
+ .instance_exec(*args, **kwargs, &block)
47
+
48
+ self
49
+ end
50
+ end
51
+ end
52
+ end
53
+ end
54
+ end
55
+ end
@@ -0,0 +1,74 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Gyros
4
+ module Features
5
+ module Scopeable
6
+ def self.included(child)
7
+ child.send(:extend, ClassMethods)
8
+ child.send(:include, InstanceMethods)
9
+
10
+ super
11
+ end
12
+
13
+ module InstanceMethods
14
+ # Returns modified scope for an action.
15
+ # Scope modifiers are defined by class-level calls to scope_for.
16
+ def scope_for(method)
17
+ result = apply_base_scopes
18
+
19
+ Array(self.class.scopes[method]).each do |scope|
20
+ result = scope.arity.positive? ? instance_exec(result, &scope) : result.instance_exec(&scope)
21
+ end
22
+
23
+ result
24
+ end
25
+
26
+ def apply_base_scopes
27
+ @new_scope = @base_scope.dup
28
+
29
+ self.class.default_scopes.each do |scope|
30
+ @new_scope = @new_scope.instance_exec(&scope)
31
+ end
32
+
33
+ @new_scope
34
+ end
35
+ end
36
+
37
+ module ClassMethods
38
+ def scopes
39
+ @scopes ||= {}
40
+ end
41
+
42
+ def default_scopes
43
+ @default_scopes ||= []
44
+ end
45
+
46
+ # Appends a block to modify model scope for an action
47
+ #
48
+ # Will be evaluated in the scope of model
49
+ # if block arity is 0:
50
+ #
51
+ # scope_for :list do
52
+ # where(id: 1)
53
+ # end
54
+ #
55
+ # Will be evaluated in the scope of resource instance
56
+ # if block arity is 1:
57
+ #
58
+ # scope_for :show do |scope|
59
+ # scope.where(id: @some_instance_variable_of_resource)
60
+ # end
61
+ def scope_for(*methods, &block)
62
+ methods.each do |method|
63
+ scopes[method] ||= []
64
+ scopes[method] << block
65
+ end
66
+ end
67
+
68
+ def default_scope(&block)
69
+ default_scopes << block
70
+ end
71
+ end
72
+ end
73
+ end
74
+ end
@@ -0,0 +1,70 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Gyros
4
+ module Features
5
+ module Sortable
6
+ def self.included(child)
7
+ child.send(:extend, ClassMethods)
8
+ child.send(:include, InstanceMethods)
9
+
10
+ super
11
+ end
12
+
13
+ module InstanceMethods
14
+ def apply(scope, params, **kwargs)
15
+ result = scope
16
+
17
+ self.class.sorters.each do |sorting|
18
+ next unless sorting.match?(params, self.class.sorting_key)
19
+
20
+ result = sorting.apply(params, result, self.class.direction_key, **kwargs)
21
+ end
22
+
23
+ super(result, params, **kwargs)
24
+ end
25
+ end
26
+
27
+ module ClassMethods
28
+ def sorters
29
+ @sorters ||= []
30
+ end
31
+
32
+ def sorters=(v)
33
+ @sorters = v
34
+ end
35
+
36
+ def sorting_key
37
+ @sorting_key ||= :sort
38
+ end
39
+
40
+ def sorting_key=(v)
41
+ @sorting_key = v
42
+ end
43
+
44
+ def direction_key
45
+ @direction_key ||= :dir
46
+ end
47
+
48
+ def direction_key=(v)
49
+ @direction_key = v
50
+ end
51
+
52
+ def respond_to_missing?(meth, *args)
53
+ Gyros::Registry.sorters.key?(meth) || super
54
+ end
55
+
56
+ def method_missing(meth, *args, &block)
57
+ if Gyros::Registry.sorters[meth]
58
+ define_singleton_method(meth) do |*args, &block|
59
+ self.sorters += Array(Gyros::Registry.sorters[meth].call(*args, &block))
60
+ end
61
+
62
+ send(meth, *args, &block)
63
+ else
64
+ super
65
+ end
66
+ end
67
+ end
68
+ end
69
+ end
70
+ end
@@ -0,0 +1,7 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'gyros/features/scopeable'
4
+ require 'gyros/features/modifiable'
5
+ require 'gyros/features/filterable'
6
+ require 'gyros/features/sortable'
7
+ require 'gyros/features/common'
@@ -0,0 +1,15 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Gyros
4
+ module Filters
5
+ class AnyOfFilter < Base
6
+ def match?(current_params)
7
+ keys.any? { |p| current_params.key?(p) }
8
+ end
9
+
10
+ def apply(result, current_params, **kwargs)
11
+ result.instance_exec(*current_params.slice(*keys).values, **kwargs, &block)
12
+ end
13
+ end
14
+ end
15
+ end
@@ -0,0 +1,27 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Gyros
4
+ module Filters
5
+ class Base
6
+ attr_reader :keys
7
+ attr_reader :block
8
+
9
+ def self.build(keys, block)
10
+ new(keys, block)
11
+ end
12
+
13
+ def initialize(keys, block)
14
+ @keys = keys
15
+ @block = block
16
+ end
17
+
18
+ def match?(_current_params)
19
+ false
20
+ end
21
+
22
+ def apply(result, _current_params, **)
23
+ result
24
+ end
25
+ end
26
+ end
27
+ end
@@ -0,0 +1,27 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Gyros
4
+ module Filters
5
+ class Filter < Base
6
+ attr_reader :keys
7
+ attr_reader :block
8
+
9
+ def self.build(keys, block)
10
+ new(keys, block)
11
+ end
12
+
13
+ def initialize(keys, block)
14
+ @keys = keys
15
+ @block = block
16
+ end
17
+
18
+ def match?(current_params)
19
+ keys.all? { |p| current_params.key?(p) }
20
+ end
21
+
22
+ def apply(result, current_params, **kwargs)
23
+ result.instance_exec(*current_params.slice(*keys).values, **kwargs, &block)
24
+ end
25
+ end
26
+ end
27
+ end
@@ -0,0 +1,38 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Gyros
4
+ module Filters
5
+ class NestedFilter < Base
6
+ include Gyros::Features::Filterable
7
+
8
+ def self.inherited(child)
9
+ child.filters ||= []
10
+
11
+ super
12
+ end
13
+
14
+ def self.build(key, block)
15
+ klass = Class.new(self)
16
+ klass.instance_exec(key, &block)
17
+ klass.new(key)
18
+ end
19
+
20
+ attr_reader :key
21
+
22
+ def initialize(key)
23
+ @key = Array(key).first
24
+ end
25
+
26
+ def match?(current_params)
27
+ current_params.has_key?(key) &&
28
+ current_params[key].is_a?(Hash)
29
+ end
30
+
31
+ def apply(result, current_params, **kwargs)
32
+ nested_params = current_params[key]
33
+
34
+ super(result, nested_params, **kwargs)
35
+ end
36
+ end
37
+ end
38
+ end
@@ -0,0 +1,18 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'gyros/filters/base'
4
+ require 'gyros/filters/filter'
5
+ require 'gyros/filters/nested_filter'
6
+ require 'gyros/filters/any_of_filter'
7
+
8
+ Gyros::Registry.register_filter :filter do |*keys, &block|
9
+ Gyros::Filters::Filter.build(keys, block)
10
+ end
11
+
12
+ Gyros::Registry.register_filter :nested_filter do |*keys, &block|
13
+ Gyros::Filters::NestedFilter.build(keys, block)
14
+ end
15
+
16
+ Gyros::Registry.register_filter :any_of_filter do |*keys, &block|
17
+ Gyros::Filters::AnyOfFilter.build(keys, block)
18
+ end
@@ -0,0 +1,39 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Gyros
4
+ class Registry
5
+ include Singleton
6
+
7
+ def self.filters
8
+ instance.filters
9
+ end
10
+
11
+ def self.sorters
12
+ instance.sorters
13
+ end
14
+
15
+ def self.register_filter(name, &block)
16
+ instance.register_filter(name, &block)
17
+ end
18
+
19
+ def self.register_sorter(name, &block)
20
+ instance.register_sorter(name, &block)
21
+ end
22
+
23
+ def filters
24
+ @filters ||= {}
25
+ end
26
+
27
+ def sorters
28
+ @sorters ||= {}
29
+ end
30
+
31
+ def register_filter(name, &block)
32
+ filters[name] = block
33
+ end
34
+
35
+ def register_sorter(name, &block)
36
+ sorters[name] = block
37
+ end
38
+ end
39
+ end
@@ -0,0 +1,27 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Gyros
4
+ module Sorters
5
+ class Base
6
+ attr_reader :key
7
+ attr_reader :block
8
+
9
+ def self.build(key, block)
10
+ new(key, block)
11
+ end
12
+
13
+ def initialize(key, block)
14
+ @key = key
15
+ @block = block
16
+ end
17
+
18
+ def match?(current_params, sorting_key)
19
+ false
20
+ end
21
+
22
+ def apply(current_params, result, direction_key)
23
+ raise NotImplementedError
24
+ end
25
+ end
26
+ end
27
+ end
@@ -0,0 +1,20 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Gyros
4
+ module Sorters
5
+ class OrderBy < Base
6
+ VALID_DIRECTIONS = [:asc, :desc].freeze
7
+
8
+ def match?(current_params, sorting_key)
9
+ current_params[sorting_key].to_s.to_sym == key
10
+ end
11
+
12
+ def apply(current_params, result, direction_key, **kwargs)
13
+ dir = current_params[direction_key].to_s.to_sym
14
+ direction = VALID_DIRECTIONS.include?(dir) ? dir : :asc
15
+
16
+ result.instance_exec(key, direction, **kwargs, &block)
17
+ end
18
+ end
19
+ end
20
+ end
@@ -0,0 +1,8 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'gyros/sorters/base'
4
+ require 'gyros/sorters/order_by'
5
+
6
+ Gyros::Registry.register_sorter :order_by do |*keys, &block|
7
+ keys.map { |key| Gyros::Sorters::OrderBy.new(key, block) }
8
+ end
@@ -0,0 +1,5 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Gyros
4
+ VERSION = "0.1.4"
5
+ end
data/lib/gyros.rb ADDED
@@ -0,0 +1,19 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'singleton'
4
+ require 'forwardable'
5
+
6
+ require 'gyros/features'
7
+
8
+ require 'gyros/registry'
9
+ require 'gyros/sorters'
10
+ require 'gyros/filters'
11
+
12
+ require 'gyros/collection'
13
+
14
+ require 'gyros/base'
15
+
16
+ require 'gyros/version'
17
+
18
+ module Gyros
19
+ end
data/sig/gyros.rbs ADDED
@@ -0,0 +1,4 @@
1
+ module Gyros
2
+ VERSION: String
3
+ # See the writing guide of rbs: https://github.com/ruby/rbs#guides
4
+ end
metadata ADDED
@@ -0,0 +1,73 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: gyros
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.4
5
+ platform: ruby
6
+ authors:
7
+ - Kirill Zaitsev
8
+ autorequire:
9
+ bindir: exe
10
+ cert_chain: []
11
+ date: 2025-05-09 00:00:00.000000000 Z
12
+ dependencies: []
13
+ description: Library which helps build queries dynamically
14
+ email:
15
+ - kirik910@gmail.com
16
+ executables: []
17
+ extensions: []
18
+ extra_rdoc_files: []
19
+ files:
20
+ - ".rspec"
21
+ - ".rubocop.yml"
22
+ - ".rubocop_todo.yml"
23
+ - CODE_OF_CONDUCT.md
24
+ - Gemfile
25
+ - Gemfile.lock
26
+ - LICENSE.txt
27
+ - README.md
28
+ - Rakefile
29
+ - lib/gyros.rb
30
+ - lib/gyros/base.rb
31
+ - lib/gyros/collection.rb
32
+ - lib/gyros/features.rb
33
+ - lib/gyros/features/common.rb
34
+ - lib/gyros/features/filterable.rb
35
+ - lib/gyros/features/modifiable.rb
36
+ - lib/gyros/features/scopeable.rb
37
+ - lib/gyros/features/sortable.rb
38
+ - lib/gyros/filters.rb
39
+ - lib/gyros/filters/any_of_filter.rb
40
+ - lib/gyros/filters/base.rb
41
+ - lib/gyros/filters/filter.rb
42
+ - lib/gyros/filters/nested_filter.rb
43
+ - lib/gyros/registry.rb
44
+ - lib/gyros/sorters.rb
45
+ - lib/gyros/sorters/base.rb
46
+ - lib/gyros/sorters/order_by.rb
47
+ - lib/gyros/version.rb
48
+ - sig/gyros.rbs
49
+ homepage: http://example.com
50
+ licenses:
51
+ - MIT
52
+ metadata:
53
+ homepage_uri: http://example.com
54
+ post_install_message:
55
+ rdoc_options: []
56
+ require_paths:
57
+ - lib
58
+ required_ruby_version: !ruby/object:Gem::Requirement
59
+ requirements:
60
+ - - ">="
61
+ - !ruby/object:Gem::Version
62
+ version: 3.0.0
63
+ required_rubygems_version: !ruby/object:Gem::Requirement
64
+ requirements:
65
+ - - ">="
66
+ - !ruby/object:Gem::Version
67
+ version: '0'
68
+ requirements: []
69
+ rubygems_version: 3.5.3
70
+ signing_key:
71
+ specification_version: 4
72
+ summary: Library which helps build queries dynamically
73
+ test_files: []