active-query 0.1.0 → 0.1.2

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 CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: 4347cec583ea17647d5682b4dd2f5b16c9ae0a0c83191347621fc178803a18f6
4
- data.tar.gz: 98e038e370148432ead3776deb5ed1ac5d2920d6c173a481f93e92f621415450
3
+ metadata.gz: 597183debb31f2b4490361200975eccbeeec9ef03e5d844abfe193e4114284d2
4
+ data.tar.gz: c82fd9b968a2dffcdd83914ea08bdc7b332453322008e41436d3f7ff7221e53e
5
5
  SHA512:
6
- metadata.gz: 85c9eb44295160425ad65161336792360e850d75b979a0ed0f795e2c302cc72edf1aa029779136dee5d63276a1d612248c8a401bc875a172d9751b8f1f7fb99c
7
- data.tar.gz: a98c8473ca1028397aa37d5240d792846563b9f3a7475d05db4a71dad4d198a218d682c3fed11dc2ddccbeed7d765188b6030def84beaef5e3c4c53a11d0aac1
6
+ metadata.gz: c8abf99aad689c83d93223dfa5de1e5e7c2ece56b6235ca6594b50f2b5413a03a06e8fb44dbf815137c3217e5eebf18335f52204450b3aab7899e7064a969d65
7
+ data.tar.gz: 8c5165ccf7c2463198e39748fcf47f5c92bc916dd5ce6f6b448e5f682c18b88fdfe05d774e385a0f716cb6bc776f822357705834878f1fe96114b2eed74bdf4e
data/.byebug_history ADDED
@@ -0,0 +1,49 @@
1
+ c
2
+ subject
3
+ c
4
+ subject
5
+ c
6
+ subject
7
+ c
8
+ subject
9
+ c
10
+ subject
11
+ c
12
+ subject
13
+ c
14
+ DummyModel.count
15
+ c
16
+ DummyModel.count
17
+ c
18
+ subject
19
+ c
20
+ const_defined?(model_class_name)
21
+ model_class_name
22
+ n
23
+ c
24
+ DummyModel.create!(name: 'Dummy')
25
+ c
26
+ DummyModel.new
27
+ DummyModel.class
28
+ DummyModel
29
+ c
30
+ DummyModel.table_name
31
+ DummyModel.class
32
+ DummyModel
33
+ DummyModel.create
34
+ DummyModel.creat
35
+ c
36
+ model_name
37
+ c
38
+ model_name
39
+ c
40
+ @__model
41
+ self.name
42
+ self
43
+ c
44
+ self.class.name
45
+ self.class
46
+ self.name
47
+ self
48
+ c
49
+ ActiveRecord::Base.connection
data/.rspec ADDED
@@ -0,0 +1,3 @@
1
+ --format documentation
2
+ --color
3
+ --require spec_helper
data/CHANGELOG.md ADDED
@@ -0,0 +1,35 @@
1
+ # Changelog
2
+
3
+ All notable changes to this project will be documented in this file.
4
+
5
+ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
6
+ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
7
+
8
+ ## [Unreleased]
9
+
10
+ ## [0.0.1] - 2024-12-19
11
+
12
+ ### Added
13
+ - Initial release of ActiveQuery gem
14
+ - Query object DSL with `ActiveQuery::Base` module
15
+ - Type validation for query arguments (String, Integer, Float, Boolean)
16
+ - Support for optional arguments and default values
17
+ - Custom scopes with `ActiveQuery::Scopes` module
18
+ - Additional query operations: `gt`, `gteq`, `lt`, `lteq`, `like`, `start_like`, `end_like`
19
+ - Resolver pattern support for complex queries
20
+ - Conditional query building with `if` and `unless` methods
21
+ - Automatic model inference from class names
22
+ - ActiveRecord integration with Rails 6.1+ support
23
+ - Comprehensive test suite with 100% code coverage
24
+ - GitHub Actions CI/CD pipeline
25
+
26
+ ### Features
27
+ - **Query Objects**: Create reusable query objects with clean DSL
28
+ - **Type Safety**: Built-in argument validation
29
+ - **Scopes**: Define custom scopes for queries
30
+ - **Operations**: Extended query operations beyond standard ActiveRecord
31
+ - **Resolvers**: Support complex query logic with resolver classes
32
+ - **Conditional Logic**: Apply scopes conditionally with `if`/`unless`
33
+
34
+ [Unreleased]: https://github.com/matiasasis/active-query/compare/v0.0.1...HEAD
35
+ [0.0.1]: https://github.com/matiasasis/active-query/releases/tag/v0.0.1
@@ -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.txt ADDED
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2024 Matias Asis
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,341 @@
1
+ # ActiveQuery
2
+
3
+ ActiveQuery is a Ruby gem that helps you create clean, reusable query objects with a simple DSL. It provides type validation, conditional logic, and seamless ActiveRecord integration.
4
+
5
+ ## Features
6
+
7
+ - **Clean Query DSL**: Define queries with clear syntax and descriptions
8
+ - **Type Safety**: Built-in argument type validation (String, Integer, Float, Boolean)
9
+ - **Optional & Default Arguments**: Flexible argument handling
10
+ - **Custom Operations**: Extended query operations like `gt`, `lt`, `like`, etc.
11
+ - **Conditional Logic**: Apply scopes conditionally with `if` and `unless`
12
+ - **Resolver Pattern**: Support for complex query logic in separate classes
13
+ - **Custom Scopes**: Define reusable scopes within query objects
14
+ - **ActiveRecord Integration**: Works seamlessly with ActiveRecord models
15
+
16
+ ## Installation
17
+
18
+ Add this line to your application's Gemfile:
19
+
20
+ ```ruby
21
+ gem 'active-query'
22
+ ```
23
+
24
+ And then execute:
25
+
26
+ ```bash
27
+ bundle install
28
+ ```
29
+
30
+ ## Usage
31
+
32
+ ### Basic Query Object
33
+
34
+ Create a query object by including `ActiveQuery::Base` and defining queries with the `query` method:
35
+
36
+ ```ruby
37
+ class UserQuery
38
+ include ActiveQuery::Base
39
+
40
+ # The model is automatically inferred from the class name (User)
41
+ # Or explicitly set it:
42
+ model_name 'User'
43
+
44
+ # Simple query without arguments
45
+ query :active, 'Returns all active users', -> { scope.where(active: true) }
46
+
47
+ # Query with arguments and type validation
48
+ query :by_email, 'Find users by email address',
49
+ { email: { type: String } },
50
+ -> (email:) { scope.where(email: email) }
51
+ end
52
+ ```
53
+
54
+ ### Using Query Objects
55
+
56
+ ```ruby
57
+ # Execute queries
58
+ active_users = UserQuery.active
59
+ user = UserQuery.by_email(email: 'john@example.com')
60
+
61
+ # Chain with ActiveRecord methods
62
+ recent_active_users = UserQuery.active.where('created_at > ?', 1.week.ago)
63
+ ```
64
+
65
+ ### Argument Types and Validation
66
+
67
+ ActiveQuery supports several argument types with automatic validation:
68
+
69
+ ```ruby
70
+ class ProductQuery
71
+ include ActiveQuery::Base
72
+
73
+ query :filter_products, 'Filter products by various criteria',
74
+ {
75
+ name: { type: String },
76
+ price: { type: Float },
77
+ quantity: { type: Integer },
78
+ available: { type: ActiveQuery::Base::Boolean }
79
+ },
80
+ -> (name:, price:, quantity:, available:) {
81
+ scope.where(name: name)
82
+ .where(price: price)
83
+ .where(quantity: quantity)
84
+ .where(available: available)
85
+ }
86
+ end
87
+
88
+ # Usage with type validation
89
+ ProductQuery.filter_products(
90
+ name: 'Widget',
91
+ price: 19.99,
92
+ quantity: 10,
93
+ available: true
94
+ )
95
+
96
+ # This will raise ArgumentError due to type mismatch
97
+ ProductQuery.filter_products(name: 123, price: 'invalid', quantity: true, available: 'yes')
98
+ ```
99
+
100
+ ### Optional Arguments and Defaults
101
+
102
+ ```ruby
103
+ class OrderQuery
104
+ include ActiveQuery::Base
105
+
106
+ query :search_orders, 'Search orders with optional filters',
107
+ {
108
+ status: { type: String },
109
+ paid: { type: ActiveQuery::Base::Boolean, default: true },
110
+ customer_name: { type: String, optional: true }
111
+ },
112
+ -> (status:, paid:, customer_name:) {
113
+ scope.where(status: status)
114
+ .where(paid: paid)
115
+ .then { |s| customer_name ? s.where('customer_name LIKE ?', "%#{customer_name}%") : s }
116
+ }
117
+ end
118
+
119
+ # Usage - customer_name is optional, paid defaults to true
120
+ OrderQuery.search_orders(status: 'pending')
121
+ OrderQuery.search_orders(status: 'completed', customer_name: 'John')
122
+ OrderQuery.search_orders(status: 'pending', paid: false, customer_name: 'Jane')
123
+ ```
124
+
125
+ ### Conditional Query Logic
126
+
127
+ Use `if` and `unless` methods for conditional query building:
128
+
129
+ ```ruby
130
+ class UserQuery
131
+ include ActiveQuery::Base
132
+
133
+ query :search_users, 'Search users with conditional filters',
134
+ {
135
+ name: { type: String, optional: true },
136
+ active: { type: ActiveQuery::Base::Boolean, optional: true }
137
+ },
138
+ -> (name:, active:) {
139
+ scope.if(name.present?, -> { where('name LIKE ?', "%#{name}%") })
140
+ .if(active == true, -> { where(active: true) })
141
+ }
142
+
143
+ query :filter_unless_admin, 'Filter users unless they are admin',
144
+ {
145
+ role: { type: String, optional: true }
146
+ },
147
+ -> (role:) {
148
+ scope.unless(role == 'admin', -> { where.not(role: 'admin') })
149
+ }
150
+ end
151
+ ```
152
+
153
+ ### Extended Query Operations
154
+
155
+ ActiveQuery provides additional query operations beyond standard ActiveRecord:
156
+
157
+ ```ruby
158
+ class ProductQuery
159
+ include ActiveQuery::Base
160
+
161
+ # Comparison operations
162
+ query :expensive_products, 'Products above price threshold', -> { scope.gt(:price, 100) }
163
+ query :affordable_products, 'Products within budget', -> { scope.lteq(:price, 50) }
164
+
165
+ # Text search operations
166
+ query :search_by_name, 'Search products by name pattern', -> { scope.like(:name, 'Phone') }
167
+ query :products_starting_with, 'Products starting with prefix', -> { scope.start_like(:name, 'iPhone') }
168
+ query :products_ending_with, 'Products ending with suffix', -> { scope.end_like(:name, 'Pro') }
169
+
170
+ # Dynamic filtering
171
+ query :by_price_range, 'Filter by price range',
172
+ { min_price: { type: Float }, max_price: { type: Float } },
173
+ -> (min_price:, max_price:) {
174
+ scope.gteq(:price, min_price)
175
+ .lteq(:price, max_price)
176
+ }
177
+ end
178
+ ```
179
+
180
+ **Available operations:**
181
+ - `gt(column, value)` - greater than
182
+ - `gteq(column, value)` - greater than or equal
183
+ - `lt(column, value)` - less than
184
+ - `lteq(column, value)` - less than or equal
185
+ - `like(column, value)` - contains pattern (wraps with %)
186
+ - `start_like(column, value)` - starts with pattern
187
+ - `end_like(column, value)` - ends with pattern
188
+
189
+ ### Custom Scopes
190
+
191
+ Define reusable scopes within your query objects:
192
+
193
+ ```ruby
194
+ class UserQuery
195
+ include ActiveQuery::Base
196
+ include ActiveQuery::Scopes
197
+
198
+ # Define custom scopes
199
+ module Scopes
200
+ include ActiveQuery::Scopes
201
+
202
+ scope :recent, -> { where('created_at > ?', 1.month.ago) }
203
+ scope :by_role, -> (role:) { where(role: role) }
204
+ end
205
+
206
+ # Use scopes in queries
207
+ query :recent_admins, 'Find recent admin users', -> { scope.recent.by_role(role: 'admin') }
208
+
209
+ query :count_recent, 'Count recent users', -> { scope.recent.count }
210
+ end
211
+ ```
212
+
213
+ ### Resolver Pattern
214
+
215
+ For complex query logic, use the resolver pattern to keep your query objects clean:
216
+
217
+ ```ruby
218
+ # Define a resolver
219
+ class UserStatsResolver < ActiveQuery::Resolver
220
+ def resolve(min_orders: 5)
221
+ scope.joins(:orders)
222
+ .group('users.id')
223
+ .having('COUNT(orders.id) >= ?', min_orders)
224
+ .select('users.*, COUNT(orders.id) as order_count')
225
+ end
226
+ end
227
+
228
+ # Use resolver in query object
229
+ class UserQuery
230
+ include ActiveQuery::Base
231
+
232
+ # Resolver without arguments
233
+ query :high_value_users, 'Users with many orders',
234
+ resolver: UserStatsResolver
235
+
236
+ # Resolver with arguments
237
+ query :users_with_orders, 'Users with minimum order count',
238
+ { min_orders: { type: Integer } },
239
+ resolver: UserStatsResolver
240
+ end
241
+
242
+ # Usage
243
+ UserQuery.high_value_users
244
+ UserQuery.users_with_orders(min_orders: 10)
245
+ ```
246
+
247
+ ### Query Introspection
248
+
249
+ Query objects provide metadata about available queries:
250
+
251
+ ```ruby
252
+ class UserQuery
253
+ include ActiveQuery::Base
254
+
255
+ query :active, 'Find active users', -> { scope.where(active: true) }
256
+ query :by_name, 'Find by name', { name: { type: String } }, -> (name:) { scope.where(name: name) }
257
+ end
258
+
259
+ # Get all available queries
260
+ UserQuery.queries
261
+ # => [
262
+ # { name: :active, description: "Find active users", args_def: {} },
263
+ # { name: :by_name, description: "Find by name", args_def: { name: { type: String } } }
264
+ # ]
265
+ ```
266
+
267
+ ### Error Handling
268
+
269
+ ActiveQuery provides clear error messages for common mistakes:
270
+
271
+ ```ruby
272
+ # Missing required arguments
273
+ UserQuery.by_email
274
+ # => ArgumentError: Params missing: [:email]
275
+
276
+ # Wrong argument type
277
+ UserQuery.by_email(email: 123)
278
+ # => ArgumentError: :email must be of type String
279
+
280
+ # Unknown arguments
281
+ UserQuery.by_email(email: 'test@example.com', invalid_param: 'value')
282
+ # => ArgumentError: Unknown params: [:invalid_param]
283
+
284
+ # Optional and default together (validation error)
285
+ query :invalid_query, 'This will fail',
286
+ { param: { type: String, optional: true, default: 'value' } },
287
+ -> (param:) { scope }
288
+ # => ArgumentError: Optional and Default params can't be present together: [:param]
289
+ ```
290
+
291
+ ### Integration with Rails
292
+
293
+ ActiveQuery works seamlessly with Rails applications:
294
+
295
+ ```ruby
296
+ # app/queries/user_query.rb
297
+ class UserQuery
298
+ include ActiveQuery::Base
299
+
300
+ query :active, 'Active users', -> { scope.where(active: true) }
301
+ query :by_role, 'Users by role', { role: { type: String } }, -> (role:) { scope.where(role: role) }
302
+ end
303
+
304
+ # In controllers
305
+ class UsersController < ApplicationController
306
+ def index
307
+ @users = UserQuery.active
308
+ end
309
+
310
+ def admins
311
+ @admins = UserQuery.by_role(role: 'admin')
312
+ end
313
+ end
314
+
315
+ # In views or anywhere else
316
+ <%= UserQuery.active.count %> active users
317
+ ```
318
+
319
+ ## Requirements
320
+
321
+ - Ruby >= 2.6.0
322
+ - ActiveRecord >= 6.1
323
+ - ActiveSupport >= 6.1
324
+
325
+ ## Development
326
+
327
+ After checking out the repo, run `bin/setup` to install dependencies. Then, run `rake spec` to run the tests. You can also run `bin/console` for an interactive prompt.
328
+
329
+ To install this gem onto your local machine, run `bundle exec rake install`. To release a new version, update the version number in `version.rb`, and then run `bundle exec rake release`.
330
+
331
+ ## Contributing
332
+
333
+ Bug reports and pull requests are welcome on GitHub at https://github.com/matiasasis/active-query. This project is intended to be a safe, welcoming space for collaboration, and contributors are expected to adhere to the [code of conduct](https://github.com/matiasasis/active-query/blob/master/CODE_OF_CONDUCT.md).
334
+
335
+ ## License
336
+
337
+ The gem is available as open source under the terms of the [MIT License](https://opensource.org/licenses/MIT).
338
+
339
+ ## Code of Conduct
340
+
341
+ Everyone interacting in the ActiveQuery project's codebases, issue trackers, chat rooms and mailing lists is expected to follow the [code of conduct](https://github.com/matiasasis/active-query/blob/master/CODE_OF_CONDUCT.md).
data/Rakefile ADDED
@@ -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
data/exe/active-query ADDED
@@ -0,0 +1,3 @@
1
+ #!/usr/bin/env ruby
2
+
3
+ require "active_query"
@@ -0,0 +1,3 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative 'active_query'
@@ -0,0 +1,11 @@
1
+ # frozen_string_literal: true
2
+
3
+ module ActiveQuery
4
+ class Resolver
5
+ attr_accessor :scope
6
+
7
+ def initialize(scope)
8
+ @scope = scope
9
+ end
10
+ end
11
+ end
@@ -0,0 +1,5 @@
1
+ # frozen_string_literal: true
2
+
3
+ module ActiveQuery
4
+ VERSION = '0.1.2'
5
+ end
data/lib/active_query.rb CHANGED
@@ -1,8 +1,193 @@
1
1
  # frozen_string_literal: true
2
2
 
3
- class ActiveQuery
4
- VERSION = "0.1.0"
5
- def self.hi
6
- 'Hello World!'
3
+ require 'active_record'
4
+ require 'active_support'
5
+ require 'active_support/concern'
6
+ require_relative 'active_query/version'
7
+ require_relative 'active_query/resolver'
8
+ require_relative 'active_record_relation_extensions'
9
+
10
+ module ActiveQuery
11
+ module Base
12
+ extend ::ActiveSupport::Concern
13
+
14
+ class Boolean; end
15
+
16
+ included do
17
+ infer_model
18
+ @__queries = []
19
+ end
20
+
21
+ class_methods do
22
+ def model_name(model_name)
23
+ classified_model_name = model_name.classify
24
+ model = classified_model_name.safe_constantize
25
+ raise NameError, "Model #{classified_model_name} not found" unless model
26
+ raise ArgumentError, 'Model should be an ActiveRecord::Base' unless model.ancestors.include?(ActiveRecord::Base)
27
+
28
+ @__model = model
29
+ end
30
+
31
+ def model
32
+ @__model
33
+ end
34
+
35
+ def scope
36
+ raise ArgumentError, "Model not defined. Add model_name('Your::Model') to your QueryObject" unless @__model
37
+
38
+ @__scope ||= begin
39
+ relation = @__model.all.extending(Operations)
40
+ relation = relation.extending(scopes_module_name.constantize) if const_defined?(scopes_module_name)
41
+ relation
42
+ end
43
+ end
44
+
45
+ # Will list all queries available on query object.
46
+ def queries
47
+ @__queries
48
+ end
49
+
50
+ def query(name, description, args_def_or_lambda = nil, lambda = nil, **kwargs)
51
+ raise ArgumentError, 'name must be present' unless name.present?
52
+
53
+ if args_def_or_lambda.is_a?(Hash)
54
+ if kwargs[:resolver].present?
55
+ query_with_resolver(name, description, args_def_or_lambda, **kwargs)
56
+ else
57
+ query_with_arguments(name, description, args_def_or_lambda, lambda)
58
+ end
59
+ elsif args_def_or_lambda.is_a?(Proc)
60
+ query_without_args(name, description, args_def_or_lambda)
61
+ elsif args_def_or_lambda.nil? && kwargs[:resolver].present?
62
+ query_with_resolver_without_out_args(name, description, **kwargs)
63
+ else
64
+ raise ArgumentError, 'Invalid query definition'
65
+ end
66
+ end
67
+
68
+ private
69
+
70
+ def scopes_module_name
71
+ "#{self}::Scopes"
72
+ end
73
+
74
+ def infer_model
75
+ model_class_name = self.name.sub(/::Query$/, '').classify
76
+ return unless const_defined?(model_class_name)
77
+
78
+ model = model_class_name.safe_constantize
79
+ return unless model.ancestors.include?(ActiveRecord::Base)
80
+
81
+ model_name(model_class_name)
82
+ end
83
+
84
+ def query_with_arguments(name, description, args_def, lambda)
85
+ register_query(name, description, args_def)
86
+
87
+ define_singleton_method(name) do |given_args|
88
+ given_args = validate_args(name, given_args, args_def)
89
+ lambda.call(**given_args)
90
+ end
91
+ end
92
+
93
+ def query_without_args(name, description, lambda)
94
+ register_query(name, description)
95
+ define_singleton_method(name) { lambda.call }
96
+ end
97
+
98
+ def query_with_resolver(name, description, args_def, **kwargs)
99
+ register_query(name, description, args_def)
100
+ resolver = kwargs[:resolver]
101
+ raise 'Invalid Resolver, must inherit from ActiveQuery::Resolvers::Base' unless resolver.ancestors.include?(ActiveQuery::Resolver)
102
+
103
+ define_singleton_method(name) do |given_args|
104
+ given_args = validate_args(name, given_args, args_def)
105
+ resolver.new(scope).resolve(**given_args)
106
+ end
107
+ end
108
+
109
+ def query_with_resolver_without_out_args(name, description, **kwargs)
110
+ register_query(name, description)
111
+ resolver = kwargs[:resolver]
112
+ raise 'Invalid Resolver, must inherit from ActiveQuery::Resolvers::Base' unless resolver.ancestors.include?(ActiveQuery::Resolver)
113
+
114
+ define_singleton_method(name) { resolver.new(scope).resolve }
115
+ end
116
+
117
+ def register_query(name, description, args_def = {})
118
+ # Validate optional and default are not present together
119
+ optional_and_default = args_def.select { |key, value| value[:optional] == true && value[:default].present? }
120
+ raise ArgumentError, "Optional and Default params can't be present together: #{optional_and_default.keys}" if optional_and_default.present?
121
+
122
+ # Will add all queries for further serving the method 'queries'
123
+ @__queries << { name:, description:, args_def: }.compact_blank
124
+ end
125
+
126
+ def validate_args(name, given_args, args_def)
127
+ # Validate if the given arguments are correct
128
+ raise ArgumentError, "Incorrect Params, must be called '.#{name}(#{args_def.keys.map { |p| "#{p}: value" }.join(', ')})' " unless given_args.is_a?(Hash)
129
+
130
+ non_optional_args = args_def.reject { |key, value| value[:optional] == true }
131
+ args_not_provided = non_optional_args.keys - given_args.keys
132
+
133
+ args_with_default_to_add = args_def.select { |key, value| value[:default].present? && args_not_provided.include?(key) }
134
+ given_args.merge!(args_with_default_to_add.map { |key, value| [key, value[:default]] }.to_h)
135
+
136
+ missing_args = non_optional_args.keys - given_args.keys
137
+ raise ArgumentError, "Params missing: #{missing_args}" unless missing_args.empty?
138
+
139
+ extra_params = given_args.keys - args_def.keys
140
+ raise ArgumentError, "Unknown params: #{extra_params}" unless extra_params.empty?
141
+
142
+ given_args.each do |given_arg|
143
+ given_arg_config = args_def[given_arg.first]
144
+ given_arg_type = given_arg_config[:type]
145
+ given_arg_name = given_arg.first
146
+ given_arg_value = given_arg.second
147
+
148
+ if given_arg_type == ActiveQuery::Base::Boolean
149
+ unless given_arg_value == true || given_arg_value == false
150
+ raise ArgumentError, ":#{given_arg_name} must be of type Boolean"
151
+ end
152
+ else
153
+ unless given_arg_value.instance_of?(given_arg_type)
154
+ raise ArgumentError, ":#{given_arg_name} must be of type #{given_arg_type}"
155
+ end
156
+ end
157
+ end
158
+
159
+ # Populates all the non optional non given arguments with nil.
160
+ not_given_args = args_def.keys - given_args.keys
161
+ given_args.merge(not_given_args.map { |key| [key, nil] }.to_h)
162
+ end
163
+ end
164
+
165
+ module Operations
166
+ def gt(col, val) = __operation(:gt, col, val)
167
+ def gteq(col, val) = __operation(:gteq, col, val)
168
+ def lt(col, val) = __operation(:lt, col, val)
169
+ def lteq(col, val) = __operation(:lteq, col, val)
170
+ def like(col, val) = __operation(:matches, col, "%#{val}%")
171
+ def start_like(col, val) = __operation(:matches, col, "#{val}%")
172
+ def end_like(col, val) = __operation(:matches, col, "%#{val}")
173
+ def __operation(op, col, val) = where(arel_table[col].send(op, val))
174
+ end
175
+ end
176
+
177
+ module Scopes
178
+ extend ActiveSupport::Concern
179
+
180
+ included do
181
+ @__scopes = []
182
+ end
183
+
184
+ class_methods do
185
+ attr_accessor :__scopes
186
+
187
+ def scope(name, lambda)
188
+ __scopes << [name, lambda]
189
+ define_method(name, &lambda)
190
+ end
191
+ end
7
192
  end
8
193
  end
@@ -0,0 +1,36 @@
1
+ # frozen_string_literal: true
2
+
3
+ module ActiveRecordRelationExtensions
4
+ extend ActiveSupport::Concern
5
+
6
+ # Adds the `if` method to ActiveRecord::Relation
7
+ module ClassMethods
8
+ # `if` applies the given scope only if the condition is true.
9
+ #
10
+ # @param if_condition [Boolean] whether to apply the scope
11
+ # @param scope [Proc] a callable object representing the scope
12
+ # @return [ActiveRecord::Relation] the modified or original relation
13
+ def if(if_condition, scope)
14
+ return self unless if_condition
15
+
16
+ raise "Invalid Scope. Must provide a lambda '-> { your_scope(arg) }'" unless scope.is_a?(Proc)
17
+
18
+ merge(scope)
19
+ end
20
+
21
+ # `if` applies the given scope only if the condition is true.
22
+ #
23
+ # @param if_condition [Boolean] whether to apply the scope
24
+ # @param scope [Proc] a callable object representing the scope
25
+ # @return [ActiveRecord::Relation] the modified or original relation
26
+ def unless(unless_condition, scope)
27
+ return self if unless_condition
28
+
29
+ raise "Invalid Scope. Must provide a lambda '-> { your_scope(arg) }'" unless scope.is_a?(Proc)
30
+
31
+ merge(scope)
32
+ end
33
+ end
34
+ end
35
+
36
+ ActiveRecord::Relation.include(ActiveRecordRelationExtensions::ClassMethods)
metadata CHANGED
@@ -1,27 +1,170 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: active-query
3
3
  version: !ruby/object:Gem::Version
4
- version: 0.1.0
4
+ version: 0.1.2
5
5
  platform: ruby
6
6
  authors:
7
7
  - Matias Asis
8
8
  autorequire:
9
- bindir: bin
9
+ bindir: exe
10
10
  cert_chain: []
11
- date: 2024-11-28 00:00:00.000000000 Z
12
- dependencies: []
13
- description:
11
+ date: 2025-08-06 00:00:00.000000000 Z
12
+ dependencies:
13
+ - !ruby/object:Gem::Dependency
14
+ name: activerecord
15
+ requirement: !ruby/object:Gem::Requirement
16
+ requirements:
17
+ - - ">="
18
+ - !ruby/object:Gem::Version
19
+ version: '6.1'
20
+ - - "<"
21
+ - !ruby/object:Gem::Version
22
+ version: '8.0'
23
+ type: :runtime
24
+ prerelease: false
25
+ version_requirements: !ruby/object:Gem::Requirement
26
+ requirements:
27
+ - - ">="
28
+ - !ruby/object:Gem::Version
29
+ version: '6.1'
30
+ - - "<"
31
+ - !ruby/object:Gem::Version
32
+ version: '8.0'
33
+ - !ruby/object:Gem::Dependency
34
+ name: activesupport
35
+ requirement: !ruby/object:Gem::Requirement
36
+ requirements:
37
+ - - ">="
38
+ - !ruby/object:Gem::Version
39
+ version: '6.1'
40
+ - - "<"
41
+ - !ruby/object:Gem::Version
42
+ version: '8.0'
43
+ type: :runtime
44
+ prerelease: false
45
+ version_requirements: !ruby/object:Gem::Requirement
46
+ requirements:
47
+ - - ">="
48
+ - !ruby/object:Gem::Version
49
+ version: '6.1'
50
+ - - "<"
51
+ - !ruby/object:Gem::Version
52
+ version: '8.0'
53
+ - !ruby/object:Gem::Dependency
54
+ name: rake
55
+ requirement: !ruby/object:Gem::Requirement
56
+ requirements:
57
+ - - "~>"
58
+ - !ruby/object:Gem::Version
59
+ version: '13.0'
60
+ type: :development
61
+ prerelease: false
62
+ version_requirements: !ruby/object:Gem::Requirement
63
+ requirements:
64
+ - - "~>"
65
+ - !ruby/object:Gem::Version
66
+ version: '13.0'
67
+ - !ruby/object:Gem::Dependency
68
+ name: rspec
69
+ requirement: !ruby/object:Gem::Requirement
70
+ requirements:
71
+ - - "~>"
72
+ - !ruby/object:Gem::Version
73
+ version: 3.9.0
74
+ type: :development
75
+ prerelease: false
76
+ version_requirements: !ruby/object:Gem::Requirement
77
+ requirements:
78
+ - - "~>"
79
+ - !ruby/object:Gem::Version
80
+ version: 3.9.0
81
+ - !ruby/object:Gem::Dependency
82
+ name: simplecov
83
+ requirement: !ruby/object:Gem::Requirement
84
+ requirements:
85
+ - - "~>"
86
+ - !ruby/object:Gem::Version
87
+ version: 0.17.1
88
+ type: :development
89
+ prerelease: false
90
+ version_requirements: !ruby/object:Gem::Requirement
91
+ requirements:
92
+ - - "~>"
93
+ - !ruby/object:Gem::Version
94
+ version: 0.17.1
95
+ - !ruby/object:Gem::Dependency
96
+ name: sqlite3
97
+ requirement: !ruby/object:Gem::Requirement
98
+ requirements:
99
+ - - "~>"
100
+ - !ruby/object:Gem::Version
101
+ version: 1.5.1
102
+ type: :development
103
+ prerelease: false
104
+ version_requirements: !ruby/object:Gem::Requirement
105
+ requirements:
106
+ - - "~>"
107
+ - !ruby/object:Gem::Version
108
+ version: 1.5.1
109
+ - !ruby/object:Gem::Dependency
110
+ name: database_cleaner-active_record
111
+ requirement: !ruby/object:Gem::Requirement
112
+ requirements:
113
+ - - "~>"
114
+ - !ruby/object:Gem::Version
115
+ version: 2.2.0
116
+ type: :development
117
+ prerelease: false
118
+ version_requirements: !ruby/object:Gem::Requirement
119
+ requirements:
120
+ - - "~>"
121
+ - !ruby/object:Gem::Version
122
+ version: 2.2.0
123
+ - !ruby/object:Gem::Dependency
124
+ name: byebug
125
+ requirement: !ruby/object:Gem::Requirement
126
+ requirements:
127
+ - - "~>"
128
+ - !ruby/object:Gem::Version
129
+ version: '11.0'
130
+ type: :development
131
+ prerelease: false
132
+ version_requirements: !ruby/object:Gem::Requirement
133
+ requirements:
134
+ - - "~>"
135
+ - !ruby/object:Gem::Version
136
+ version: '11.0'
137
+ description: ActiveQuery is a gem that helps you to create query objects in a simple
138
+ way. It provides a DSL to define queries and scopes for your query object.
14
139
  email:
15
140
  - matiasis.90@gmail.com
16
- executables: []
141
+ executables:
142
+ - active-query
17
143
  extensions: []
18
144
  extra_rdoc_files: []
19
145
  files:
146
+ - ".byebug_history"
147
+ - ".rspec"
148
+ - CHANGELOG.md
149
+ - CODE_OF_CONDUCT.md
150
+ - LICENSE.txt
151
+ - README.md
152
+ - Rakefile
153
+ - exe/active-query
154
+ - lib/active-query.rb
20
155
  - lib/active_query.rb
156
+ - lib/active_query/resolver.rb
157
+ - lib/active_query/version.rb
158
+ - lib/active_record_relation_extensions.rb
21
159
  homepage: https://github.com/matiasasis/active-query
22
160
  licenses:
23
161
  - MIT
24
- metadata: {}
162
+ metadata:
163
+ homepage_uri: https://github.com/matiasasis/active-query
164
+ source_code_uri: https://github.com/matiasasis/active-query
165
+ bug_tracker_uri: https://github.com/matiasasis/active-query/issues
166
+ changelog_uri: https://github.com/matiasasis/active-query/blob/master/CHANGELOG.md
167
+ rubygems_mfa_required: 'true'
25
168
  post_install_message:
26
169
  rdoc_options: []
27
170
  require_paths:
@@ -37,8 +180,8 @@ required_rubygems_version: !ruby/object:Gem::Requirement
37
180
  - !ruby/object:Gem::Version
38
181
  version: '0'
39
182
  requirements: []
40
- rubygems_version: 3.5.23
183
+ rubygems_version: 3.4.15
41
184
  signing_key:
42
185
  specification_version: 4
43
- summary: This is active-query
186
+ summary: ActiveQuery is a gem that helps you to create query objects in a simple way.
44
187
  test_files: []