Last active
November 5, 2024 19:54
-
-
Save Hasstrup/1a3446b94035da0f8c655965b27f1a6e to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# frozen_string_literal: true | |
module Queries | |
# The Engine module provides a structure for executing queries against | |
# a given model with a defined set of parameters and conditions. | |
module Engine | |
def self.call(**kwargs) | |
new(**kwargs).call | |
end | |
def initialize(params:, type: :group) | |
@params = params.sanitize! | |
@type = type | |
end | |
# Executes the query and handles success or failure. | |
# | |
# @return [Context] The context containing the result of the query. | |
def call | |
safely_execute do | |
relation = scope!(klass.where(params.conditions).includes(params.includes)) | |
raise ActiveRecord::RecordNotFound if single? && relation&.empty? | |
context.succeed(single? ? relation.first : relation) | |
end | |
end | |
private | |
attr_reader :params, :type | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment