Skip to content

Instantly share code, notes, and snippets.

@Hasstrup
Last active November 5, 2024 19:54
Show Gist options
  • Save Hasstrup/1a3446b94035da0f8c655965b27f1a6e to your computer and use it in GitHub Desktop.
Save Hasstrup/1a3446b94035da0f8c655965b27f1a6e to your computer and use it in GitHub Desktop.
# 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