active-query 0.0.1
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/.byebug_history +49 -0
- data/.rspec +3 -0
- data/CHANGELOG.md +35 -0
- data/CODE_OF_CONDUCT.md +132 -0
- data/LICENSE.txt +21 -0
- data/README.md +208 -0
- data/Rakefile +8 -0
- data/exe/active-query +3 -0
- data/lib/active_query/resolver.rb +11 -0
- data/lib/active_query/version.rb +5 -0
- data/lib/active_query.rb +193 -0
- data/lib/active_record_relation_extensions.rb +36 -0
- metadata +186 -0
checksums.yaml
ADDED
@@ -0,0 +1,7 @@
|
|
1
|
+
---
|
2
|
+
SHA256:
|
3
|
+
metadata.gz: 94e95d436673389768c5ee9999d7b8d144a70a6b718411a24cdde34a5281cbba
|
4
|
+
data.tar.gz: c427212727750ff677b1200bf191e0abb531b428389028e53db74c162be847c7
|
5
|
+
SHA512:
|
6
|
+
metadata.gz: f1422b5d9bcf688fe25affe8f87dc108341c53194f417e4ec9a10c86f67c37346d3cadfe369a5f54c9e118b3fd96033b43310f2f96c1f2c5095fa40390f3b96a
|
7
|
+
data.tar.gz: 2a77ffdf0ec0e257b121cec50ccc3113c9d43dde0202e37531ad56782aa963dd0de302932d3b683cb2167f9766e3f4636fba1be1fdfe3ad30e3027baf9e8cfd6
|
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
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
|
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.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,208 @@
|
|
1
|
+
# ActiveQuery
|
2
|
+
|
3
|
+
ActiveQuery is a gem that helps you create query objects in a simple way. It provides a DSL to define queries and scopes for your query object, making it easier to organize and reuse complex database queries.
|
4
|
+
|
5
|
+
## Features
|
6
|
+
|
7
|
+
- **Query Objects**: Create reusable query objects with a clean DSL
|
8
|
+
- **Type Validation**: Built-in argument type validation
|
9
|
+
- **Scopes**: Define custom scopes for your queries
|
10
|
+
- **Operations**: Additional query operations like `gt`, `lt`, `like`, etc.
|
11
|
+
- **Resolvers**: Support for resolver pattern for complex queries
|
12
|
+
- **ActiveRecord Integration**: Works seamlessly with ActiveRecord models
|
13
|
+
|
14
|
+
## Installation
|
15
|
+
|
16
|
+
Add this line to your application's Gemfile:
|
17
|
+
|
18
|
+
```ruby
|
19
|
+
gem 'active-query'
|
20
|
+
```
|
21
|
+
|
22
|
+
And then execute:
|
23
|
+
|
24
|
+
```bash
|
25
|
+
bundle install
|
26
|
+
```
|
27
|
+
|
28
|
+
Or install it yourself as:
|
29
|
+
|
30
|
+
```bash
|
31
|
+
gem install active-query
|
32
|
+
```
|
33
|
+
|
34
|
+
## Usage
|
35
|
+
|
36
|
+
### Basic Query Object
|
37
|
+
|
38
|
+
Create a query object by including `ActiveQuery::Base`:
|
39
|
+
|
40
|
+
```ruby
|
41
|
+
class UserQuery
|
42
|
+
include ActiveQuery::Base
|
43
|
+
|
44
|
+
# The model is automatically inferred from the class name (User)
|
45
|
+
# Or you can explicitly set it:
|
46
|
+
# model_name 'User'
|
47
|
+
|
48
|
+
query :by_email, 'Find users by email', { email: { type: String } } do |email:|
|
49
|
+
scope.where(email: email)
|
50
|
+
end
|
51
|
+
|
52
|
+
query :active, 'Find active users' do
|
53
|
+
scope.where(active: true)
|
54
|
+
end
|
55
|
+
end
|
56
|
+
```
|
57
|
+
|
58
|
+
### Using Query Objects
|
59
|
+
|
60
|
+
```ruby
|
61
|
+
# Find users by email
|
62
|
+
users = UserQuery.by_email(email: 'john@example.com')
|
63
|
+
|
64
|
+
# Find active users
|
65
|
+
active_users = UserQuery.active
|
66
|
+
|
67
|
+
# Chain queries
|
68
|
+
active_users_with_email = UserQuery.active.by_email(email: 'john@example.com')
|
69
|
+
```
|
70
|
+
|
71
|
+
### Query Arguments with Types
|
72
|
+
|
73
|
+
```ruby
|
74
|
+
class ProductQuery
|
75
|
+
include ActiveQuery::Base
|
76
|
+
|
77
|
+
query :by_price_range, 'Find products within price range', {
|
78
|
+
min_price: { type: Float },
|
79
|
+
max_price: { type: Float, optional: true },
|
80
|
+
include_tax: { type: ActiveQuery::Base::Boolean, default: false }
|
81
|
+
} do |min_price:, max_price:, include_tax:|
|
82
|
+
scope.where('price >= ?', min_price)
|
83
|
+
.then { |s| max_price ? s.where('price <= ?', max_price) : s }
|
84
|
+
.then { |s| include_tax ? s.where(tax_included: true) : s }
|
85
|
+
end
|
86
|
+
end
|
87
|
+
|
88
|
+
# Usage
|
89
|
+
products = ProductQuery.by_price_range(min_price: 10.0, max_price: 100.0, include_tax: true)
|
90
|
+
```
|
91
|
+
|
92
|
+
### Custom Scopes
|
93
|
+
|
94
|
+
Define reusable scopes within your query object:
|
95
|
+
|
96
|
+
```ruby
|
97
|
+
class OrderQuery
|
98
|
+
include ActiveQuery::Base
|
99
|
+
include ActiveQuery::Scopes
|
100
|
+
|
101
|
+
scope :recent, -> { where('created_at > ?', 1.week.ago) }
|
102
|
+
scope :completed, -> { where(status: 'completed') }
|
103
|
+
|
104
|
+
query :recent_completed, 'Find recent completed orders' do
|
105
|
+
scope.recent.completed
|
106
|
+
end
|
107
|
+
end
|
108
|
+
```
|
109
|
+
|
110
|
+
### Operations
|
111
|
+
|
112
|
+
ActiveQuery provides additional query operations:
|
113
|
+
|
114
|
+
```ruby
|
115
|
+
class UserQuery
|
116
|
+
include ActiveQuery::Base
|
117
|
+
|
118
|
+
query :by_age_range, 'Find users by age range', {
|
119
|
+
min_age: { type: Integer, optional: true },
|
120
|
+
max_age: { type: Integer, optional: true }
|
121
|
+
} do |min_age:, max_age:|
|
122
|
+
scope.then { |s| min_age ? s.gteq(:age, min_age) : s }
|
123
|
+
.then { |s| max_age ? s.lteq(:age, max_age) : s }
|
124
|
+
end
|
125
|
+
|
126
|
+
query :by_name, 'Find users by name pattern', { name: { type: String } } do |name:|
|
127
|
+
scope.like(:name, name)
|
128
|
+
end
|
129
|
+
end
|
130
|
+
```
|
131
|
+
|
132
|
+
Available operations:
|
133
|
+
- `gt(column, value)` - greater than
|
134
|
+
- `gteq(column, value)` - greater than or equal
|
135
|
+
- `lt(column, value)` - less than
|
136
|
+
- `lteq(column, value)` - less than or equal
|
137
|
+
- `like(column, value)` - contains pattern
|
138
|
+
- `start_like(column, value)` - starts with pattern
|
139
|
+
- `end_like(column, value)` - ends with pattern
|
140
|
+
|
141
|
+
### Resolvers
|
142
|
+
|
143
|
+
For complex queries, you can use the resolver pattern:
|
144
|
+
|
145
|
+
```ruby
|
146
|
+
class UserStatsResolver < ActiveQuery::Resolver
|
147
|
+
def resolve(status: nil)
|
148
|
+
query = scope.joins(:orders)
|
149
|
+
query = query.where(status: status) if status
|
150
|
+
query.group(:id).having('COUNT(orders.id) > 5')
|
151
|
+
end
|
152
|
+
end
|
153
|
+
|
154
|
+
class UserQuery
|
155
|
+
include ActiveQuery::Base
|
156
|
+
|
157
|
+
query :with_many_orders, 'Users with many orders', {
|
158
|
+
status: { type: String, optional: true }
|
159
|
+
}, resolver: UserStatsResolver
|
160
|
+
end
|
161
|
+
|
162
|
+
# Usage
|
163
|
+
users = UserQuery.with_many_orders(status: 'active')
|
164
|
+
```
|
165
|
+
|
166
|
+
### Conditional Queries
|
167
|
+
|
168
|
+
Use `if` and `unless` for conditional query building:
|
169
|
+
|
170
|
+
```ruby
|
171
|
+
class ProductQuery
|
172
|
+
include ActiveQuery::Base
|
173
|
+
|
174
|
+
query :search, 'Search products', {
|
175
|
+
name: { type: String, optional: true },
|
176
|
+
category: { type: String, optional: true },
|
177
|
+
on_sale: { type: ActiveQuery::Base::Boolean, optional: true }
|
178
|
+
} do |name:, category:, on_sale:|
|
179
|
+
scope.if(name.present?, -> { where('name ILIKE ?', "%#{name}%") })
|
180
|
+
.if(category.present?, -> { where(category: category) })
|
181
|
+
.if(on_sale == true, -> { where('sale_price IS NOT NULL') })
|
182
|
+
end
|
183
|
+
end
|
184
|
+
```
|
185
|
+
|
186
|
+
## Requirements
|
187
|
+
|
188
|
+
- Ruby >= 2.6.0
|
189
|
+
- ActiveRecord >= 6.1
|
190
|
+
- ActiveSupport >= 6.1
|
191
|
+
|
192
|
+
## Development
|
193
|
+
|
194
|
+
After checking out the repo, run `bin/setup` to install dependencies. Then, run `rake spec` to run the tests. You can also run `bin/console` for an interactive prompt that will allow you to experiment.
|
195
|
+
|
196
|
+
To install this gem onto your local machine, run `bundle exec rake install`. To release a new version, update the version number in `version.rb`, and then run `bundle exec rake release`, which will create a git tag for the version, push git commits and the created tag, and push the `.gem` file to [rubygems.org](https://rubygems.org).
|
197
|
+
|
198
|
+
## Contributing
|
199
|
+
|
200
|
+
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).
|
201
|
+
|
202
|
+
## License
|
203
|
+
|
204
|
+
The gem is available as open source under the terms of the [MIT License](https://opensource.org/licenses/MIT).
|
205
|
+
|
206
|
+
## Code of Conduct
|
207
|
+
|
208
|
+
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
data/exe/active-query
ADDED
data/lib/active_query.rb
ADDED
@@ -0,0 +1,193 @@
|
|
1
|
+
# frozen_string_literal: true
|
2
|
+
|
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
|
192
|
+
end
|
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
ADDED
@@ -0,0 +1,186 @@
|
|
1
|
+
--- !ruby/object:Gem::Specification
|
2
|
+
name: active-query
|
3
|
+
version: !ruby/object:Gem::Version
|
4
|
+
version: 0.0.1
|
5
|
+
platform: ruby
|
6
|
+
authors:
|
7
|
+
- Matias Asis
|
8
|
+
autorequire:
|
9
|
+
bindir: exe
|
10
|
+
cert_chain: []
|
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.
|
139
|
+
email:
|
140
|
+
- matiasis.90@gmail.com
|
141
|
+
executables:
|
142
|
+
- active-query
|
143
|
+
extensions: []
|
144
|
+
extra_rdoc_files: []
|
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
|
155
|
+
- lib/active_query/resolver.rb
|
156
|
+
- lib/active_query/version.rb
|
157
|
+
- lib/active_record_relation_extensions.rb
|
158
|
+
homepage: https://github.com/matiasasis/active-query
|
159
|
+
licenses:
|
160
|
+
- MIT
|
161
|
+
metadata:
|
162
|
+
homepage_uri: https://github.com/matiasasis/active-query
|
163
|
+
source_code_uri: https://github.com/matiasasis/active-query
|
164
|
+
bug_tracker_uri: https://github.com/matiasasis/active-query/issues
|
165
|
+
changelog_uri: https://github.com/matiasasis/active-query/blob/master/CHANGELOG.md
|
166
|
+
rubygems_mfa_required: 'true'
|
167
|
+
post_install_message:
|
168
|
+
rdoc_options: []
|
169
|
+
require_paths:
|
170
|
+
- lib
|
171
|
+
required_ruby_version: !ruby/object:Gem::Requirement
|
172
|
+
requirements:
|
173
|
+
- - ">="
|
174
|
+
- !ruby/object:Gem::Version
|
175
|
+
version: 2.6.0
|
176
|
+
required_rubygems_version: !ruby/object:Gem::Requirement
|
177
|
+
requirements:
|
178
|
+
- - ">="
|
179
|
+
- !ruby/object:Gem::Version
|
180
|
+
version: '0'
|
181
|
+
requirements: []
|
182
|
+
rubygems_version: 3.4.15
|
183
|
+
signing_key:
|
184
|
+
specification_version: 4
|
185
|
+
summary: ActiveQuery is a gem that helps you to create query objects in a simple way.
|
186
|
+
test_files: []
|