restme 0.0.37

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: 1b1c3586a14caa25fa15e0d7bcaf12547738e779d43e498c9241dbb198990cbb
4
+ data.tar.gz: 5ded53d0db89650ebab2580d512912a5939998347367fb7414dbdd07ace50c3e
5
+ SHA512:
6
+ metadata.gz: 982f4ca537611174ec4a2ef7a768c26e33869b5491fab6ad58ea09189fe21fa9d35875f580982ccbb392ebd13c3d0fa3c8b8d4c5777e4fa4245e80b2585e8520
7
+ data.tar.gz: 179e7b1f1f7d6604498ac40265c9f0e187781f0432f559997959af21934ef92b46e72fdffb8cfb52ce072af91c7a36695c830a8ddf8822e9453e860fbaed7aa9
data/.rspec ADDED
@@ -0,0 +1,3 @@
1
+ --format documentation
2
+ --color
3
+ --require spec_helper
data/.rubocop.yml ADDED
@@ -0,0 +1,8 @@
1
+ AllCops:
2
+ TargetRubyVersion: 3.0
3
+
4
+ Style/StringLiterals:
5
+ EnforcedStyle: double_quotes
6
+
7
+ Style/StringLiteralsInInterpolation:
8
+ EnforcedStyle: double_quotes
data/CHANGELOG.md ADDED
@@ -0,0 +1,5 @@
1
+ ## [Unreleased]
2
+
3
+ ## [0.1.0] - 2025-04-26
4
+
5
+ - Initial release
@@ -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/Dockerfile ADDED
@@ -0,0 +1,28 @@
1
+ FROM ruby:3.4.3
2
+
3
+ RUN apt-get update -y ; apt-get upgrade -y openssl
4
+ RUN apt-get install -y unrar-free build-essential libpq-dev cmake vim poppler-utils postgresql-client
5
+
6
+ RUN useradd -c 'restme' -m -d /home/restme -s /bin/bash restme
7
+
8
+ ENV DISPLAY=:99
9
+ ENV RUBY_GC_MALLOC_LIMIT=90000000
10
+ ENV RUBY_GC_HEAP_FREE_SLOTS=200000
11
+ ENV APP_HOME=/var/www/restme
12
+
13
+ RUN mkdir -p $APP_HOME
14
+
15
+ WORKDIR $APP_HOME
16
+
17
+ ADD Gemfile* $APP_HOME/
18
+
19
+ RUN chown -R $(whoami):$(whoami) $APP_HOME
20
+
21
+ RUN gem install bundler \
22
+ && bundle install --jobs 3
23
+
24
+ ADD . $APP_HOME
25
+
26
+ EXPOSE 3000
27
+
28
+ CMD ["./bin/rails", "server"]
data/LICENSE.txt ADDED
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2025 TODO: Write your name
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,350 @@
1
+ # Restme
2
+
3
+ ## ⚠️ Do not use this gem yet. In progress
4
+
5
+ [![Gem Version](https://badge.fury.io/rb/restme.svg)](https://badge.fury.io/rb/restme)
6
+
7
+ Adds support for new **Rails** controller actions such as pagination, filtering, sorting, and selecting specific model fields. Easily implement full CRUD functionality by importing Restme into your controller.
8
+
9
+ This gem manages your controller's responsibilities for:
10
+ - Read Actions: Provide complete pagination, filtering, sorting, and field selection for records, all handled through query parameters (e.g., `http://127.0.0.1/products?name_equal=foo`).
11
+ - Create/Update Actions: Enabling automatic creation and updating of records.
12
+
13
+ ## Installation
14
+
15
+
16
+
17
+ ```bash
18
+ gem install restme
19
+ ```
20
+
21
+ OR
22
+
23
+ ```bash
24
+ gem 'restme', '~> 0.0.33'
25
+ ```
26
+
27
+ ## Usage
28
+
29
+ #### ℹ️ Current Version of gem require the following pré configs
30
+
31
+ - If your controller defines an instance variable named `current_user`, Restme will automatically assign it to `model.current_user` during create and update actions—provided your model responds to the `current_user` method.
32
+ - Your user model must have a role attribute (user.role).
33
+ - Your controllers must be named using the plural form of the model (e.g., Product → ProductsController). Alternatively, you can manually set the model name by defining the MODEL_NAME constant (e.g., MODEL_NAME = "Shopping").
34
+ - You must create a folder inside app named restfy to define controller rules for authorization, scoping, creation, updating, and field selection (see example below).
35
+
36
+
37
+ ### Usage examples
38
+
39
+
40
+ #### First of all
41
+
42
+ Include the Restme module in your controller (or, optionally, in your ApplicationController if you want it available globally):
43
+ ```ruby
44
+ include Restme::Restme
45
+
46
+ before_action :initialize_restme # This will authorize or deny the current action based on `ProductsController::Authorize::Rules` (see example below)
47
+ ```
48
+
49
+ <br>
50
+ <br>
51
+
52
+ ProductsController example with restme
53
+ ```ruby
54
+ module Api::V1::Products
55
+ class ProductsController < ApplicationController
56
+ include Restme::Restme
57
+
58
+ before_action :initialize_restme
59
+
60
+ def index
61
+ render json: pagination_response, status: restme_scope_status
62
+ end
63
+
64
+ def show
65
+ render json: model_scope_object, status: restme_scope_status
66
+ end
67
+
68
+ def create
69
+ render json: creatable_record, status: restme_create_status
70
+ end
71
+
72
+ def update
73
+ render json: updateable_record, status: restme_update_status
74
+ end
75
+ end
76
+ end
77
+ ```
78
+ - `restme_scope_status`, `restme_create_status`, and `restme_update_status` are dynamic status codes generated by Restme.
79
+ - `model_scope_object` returns a single record or nil base on scope users.
80
+ - `pagination_response` returns the dynamic collection response generated by Restme.
81
+
82
+ <be><br>
83
+
84
+ Each Restme controller works together with its corresponding rules defined inside app/restfy. Restme dynamically loads the rules for each controller.
85
+
86
+ For example, ProductsController has the following rules:
87
+
88
+ ### app/restfy/products_controller/authorize/rules.rb
89
+ - Used to verify if a user is authorized to access the current action based on their role.
90
+ ```ruby
91
+ module ProductsController::Authorize
92
+ class Rules
93
+ ALLOWED_ROLES_ACTIONS = {
94
+ create: %i[manager],
95
+ index: %i[client manager],
96
+ show: %i[client manager],
97
+ update: %i[manager]
98
+ }.freeze
99
+ end
100
+ end
101
+ ```
102
+
103
+ ### app/restfy/products_controller/create/rules.rb
104
+ - Used to check if the current create action is within the user's scope. The example below checks if a manager is authorized to create a product for a specific establishment_id.
105
+ - `CREATABLE_ACTIONS_RULES` defines which controller actions are considered POST actions.
106
+ ```ruby
107
+ module ProductsController::Create
108
+ class Rules
109
+ CREATABLE_ACTIONS_RULES = %i[create].freeze
110
+
111
+ # The initialization of the create rules must receive the following three parameters: current_record (the record in memory), current_user, and the controller's params.
112
+ def initialize(temp_record, current_user, controller_params = {})
113
+ @temp_record = temp_record
114
+ @current_user = current_user
115
+ @controller_params = controller_params
116
+ end
117
+
118
+ def create_manager_scope?
119
+ @current_user.manager.establishments.exists?(id: @temp_record.establishment_id)
120
+ end
121
+ end
122
+ end
123
+
124
+ ```
125
+
126
+
127
+ ### app/restfy/products_controller/update/rules.rb
128
+ - Used to check if the current update action is within the user's scope. The example below checks if a manager is authorized to update a product for a specific establishment_id.
129
+ - `UPDATABLE_ACTIONS_RULES` defines which controller actions are considered PUT actions.
130
+ ```ruby
131
+ module ProductsController::Update
132
+ class Rules
133
+ UPDATABLE_ACTIONS_RULES = %i[update].freeze
134
+
135
+ # The initialization of the create rules must receive the following three parameters: current_record (the record in memory), current_user, and the controller's params.
136
+ def initialize(temp_record, current_user, controller_params = {})
137
+ @temp_record = temp_record
138
+ @current_user = current_user
139
+ @controller_params = controller_params
140
+ end
141
+
142
+ def update_manager_scope?
143
+ @current_user.manager.establishments.select(:id).ids.include?(@temp_record.establishment_id)
144
+ end
145
+ end
146
+ end
147
+
148
+ ```
149
+
150
+
151
+ ### app/restfy/products_controller/scope/rules.rb
152
+ This rule defines which records are part of the current user's scope (i.e., visible to them).
153
+ ```ruby
154
+ module ProductsController::Scope
155
+ class Rules
156
+
157
+ # The initialization of the scope rules must receive the following three parameters: current_record (the record in memory), current_user, and the controller's params.
158
+ def initialize(klass, current_user, controller_params = {})
159
+ @klass = klass
160
+ @current_user = current_user
161
+ @controller_params = controller_params
162
+ end
163
+
164
+ def client_scope
165
+ @klass.all
166
+ end
167
+
168
+ def deliveryman_scope
169
+ @klass.all
170
+ end
171
+
172
+ def manager_scope
173
+ @klass.where(establishment_id: @current_user.manager.establishments.ids)
174
+ end
175
+ end
176
+ end
177
+ ```
178
+
179
+
180
+ ### app/restfy/products_controller/field/rules.rb
181
+ This rule defines which nested_fields are selectable (nested fields are model relationships).
182
+ ```ruby
183
+ module ProductsController::Field
184
+ class Rules
185
+ NESTED_SELECTABLE_FIELDS = {
186
+ unit: {
187
+ table_name: :units
188
+ },
189
+ establishment: {
190
+ table_name: :establishments
191
+ },
192
+ category: {
193
+ table_name: :categories
194
+ }
195
+ }.freeze
196
+ end
197
+ end
198
+ ```
199
+
200
+ ### And now how to use that?
201
+
202
+ <br><br>
203
+
204
+ #### Filtering
205
+
206
+ To enable data filtering, specify the filterable fields in your model using the `FILTERABLE_FIELDS` constant (e.g., `FILTERABLE_FIELDS = %[name]`).
207
+
208
+ You can filter data using the following query parameters:
209
+
210
+ - **in**: Filters by matching any of the specified values.
211
+ - Example: `id_in=1,2,3`
212
+
213
+ - **equal**: Filters by exact match.
214
+ - Example: `name_equal=foo`
215
+
216
+ - **like**: Filters by partial match (using `LIKE` SQL operator).
217
+ - Example: `name_like=foo`
218
+
219
+ - **bigger_than**: Filters by records where the field is greater than the specified value.
220
+ - Example: `created_at_bigger_than=2025-01-01`
221
+
222
+ - **less_than**: Filters by records where the field is less than the specified value.
223
+ - Example: `created_at_less_than=2025-01-01`
224
+
225
+ - **bigger_than_or_equal_to**: Filters by records where the field is greater than or equal to the specified value.
226
+ - Example: `created_at_bigger_than_or_equal_to=2025-01-01`
227
+
228
+ - **less_than_or_equal_to**: Filters by records where the field is less than or equal to the specified value.
229
+ - Example: `created_at_less_than_or_equal_to=2025-01-01`
230
+
231
+ Example request:
232
+
233
+ ```
234
+ http://127.0.0.1/api/v1/products?name_equal=foo,establishment_id_in=1,2,3
235
+ ```
236
+
237
+ <br><br>
238
+
239
+
240
+ #### Sorting
241
+
242
+ To enable data sorting, specify the sortable fields in your model using the `SORTABLE_FIELDS` constant (e.g., `SORTABLE_FIELDS = %[id]`).
243
+
244
+ You can sort records using the following query parameters:
245
+
246
+ Examples
247
+
248
+ - **Descending (DESC)**: Sort records in descending order.
249
+ ```bash
250
+ http://localhost:3000/api/v1/products?id_sort=desc
251
+ ```
252
+
253
+ - Ascending (ASC): Sort records in ascending order.
254
+ ```bash
255
+ http://localhost:3000/api/v1/products?id_sort=asc
256
+ ```
257
+
258
+ <br><br>
259
+
260
+
261
+ #### Pagination
262
+
263
+ Pagination functionality is available for any `index` endpoint that uses the `pagination_response` variable in the controller.
264
+
265
+ There are two query parameters available to control pagination:
266
+ - `per_page`: Defines the number of items per page.
267
+ - `page`: Sets the current page number.
268
+
269
+ ℹ️ **Note:** The maximum number of items per page is currently limited to 100.
270
+
271
+ Example usage:
272
+
273
+ ```bash
274
+ http://localhost:3000/api/v1/products?per_page=12&page=1
275
+ ```
276
+
277
+ <br><br>
278
+
279
+
280
+ #### Field Selection (`fields_select`)
281
+
282
+ You can select specific fields from your model, such as `id`, `name`, or `created_at`.
283
+ The resulting query will retrieve **only** the selected fields directly from the database, improving performance.
284
+
285
+ Example:
286
+
287
+ ```bash
288
+ http://localhost:3000/api/v1/products?fields_select=id,name
289
+ ```
290
+
291
+ <br><br>
292
+
293
+
294
+ #### Nested Field Selection (`nested_fields_select`)
295
+
296
+ You can also select specific relationships of your records, such as `product.client` or `product.establishment`.
297
+ The resulting query will automatically include the related data, optimizing the response for your needs.
298
+
299
+ ℹ️ **Note:**
300
+ If you select a nested field, you must also ensure that the related foreign key (e.g., `establishment_id`, `client_id`) is included via `fields_select`.
301
+ If the `fields_select` parameter is not provided, Restme will automatically handle the necessary field selections.
302
+
303
+ Example:
304
+
305
+ ```bash
306
+ http://localhost:3000/api/v1/products?nested_fields_select=client
307
+ ```
308
+
309
+ ```json
310
+ {
311
+ "products": [
312
+ {
313
+ "id": 1,
314
+ "name": "foo",
315
+ "client": {
316
+ "id": 5,
317
+ "name": "bar"
318
+ }
319
+ }
320
+ ]
321
+ }
322
+ ```
323
+
324
+ <br><br>
325
+
326
+
327
+ #### Attachment Field Selection (`attachment_fields_select`)
328
+
329
+ If your model uses Active Storage and has attachments, you can retrieve the URL of an attached file by using the `attachment_fields_select` parameter.
330
+ When specified, Restme will include the URL of the attachment in the response.
331
+
332
+ ℹ️ **Note:**
333
+ If the specified attachment field does not exist in the model, Restme will return an HTTP 422 Unprocessable Entity error.
334
+
335
+ Example:
336
+
337
+ ```bash
338
+ http://localhost:3000/api/v1/products?attachment_fields_select=image
339
+ ```
340
+
341
+ <br><br>
342
+
343
+
344
+ ## License
345
+
346
+ The gem is available as open source under the terms of the [MIT License](https://opensource.org/licenses/MIT).
347
+
348
+ ## Code of Conduct
349
+
350
+ Everyone interacting in the Restme project's codebases, issue trackers, chat rooms and mailing lists is expected to follow the [code of conduct](https://github.com/[USERNAME]/restme/blob/master/CODE_OF_CONDUCT.md).
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]
@@ -0,0 +1,13 @@
1
+ services:
2
+ restme_app:
3
+ build:
4
+ context: .
5
+ dockerfile: Dockerfile
6
+ container_name: restme
7
+ command: /bin/bash
8
+ tty: true
9
+ volumes:
10
+ - .:/var/www/restme
11
+ mem_limit: 1024mb
12
+ volumes:
13
+ app:
@@ -0,0 +1,35 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "../shared/user_role"
4
+ require_relative "../shared/current_model"
5
+
6
+ module Restme
7
+ module Authorize
8
+ # Defines the rules used to authotize user
9
+ module Rules
10
+ include ::Restme::Shared::CurrentModel
11
+ include ::Restme::Shared::UserRole
12
+
13
+ def user_authorize
14
+ return true unless restme_current_user
15
+ return if super_authorize? || allowed_roles_actions[action_name.to_sym]&.include?(user_role.to_sym)
16
+
17
+ render json: { message: "Action not allowed" }, status: :forbidden
18
+ end
19
+
20
+ def allowed_roles_actions
21
+ return {} unless authorize_rules_class.const_defined?(:ALLOWED_ROLES_ACTIONS)
22
+
23
+ authorize_rules_class::ALLOWED_ROLES_ACTIONS
24
+ end
25
+
26
+ def super_authorize?
27
+ restme_current_user&.super_admin?
28
+ end
29
+
30
+ def authorize_rules_class
31
+ "#{controller_class.to_s.split("::").last}::Authorize::Rules".constantize
32
+ end
33
+ end
34
+ end
35
+ end