module CQL::ActiveRecord::Scopes

Overview

The Scopes module provides a way to define reusable query logic that can be chained with other query methods, similar to Rails ActiveRecord scopes.

Features

Examples

class Article
  include CQL::ActiveRecord::Model(Int64)
  db_context AcmeDB, :posts

  property title : String = ""
  property user_id : Int64 = 0_i64
  property published : Bool = false
  property created_at : Time?

  # Simple scope without parameters
  scope :published, -> { where(published: true) }

  # Parameterized scope
  scope :by_author, ->(user_id : Int64) { where(user_id: user_id) }

  # Scope with a typed condition
  scope :recent, ->(days : Int32) { where { created_at > days.days.ago } }

  # Scope that calls other scopes
  scope :published_by, ->(user_id : Int64) { published.by_author(user_id) }

  def initialize
  end
end

# Usage examples:
Article.published.all                                    # Simple scope
Article.by_author(1_i64).all                             # Parameterized scope
Article.published.by_author(1_i64).all                   # Chained scopes
Article.recent(30).count                                 # Scope with parameter
Article.published.recent(7).order(created_at: :desc).all # Mixed with query methods

Defined in:

active_record/scopes.cr

Class Method Summary

Macro Summary

Class Method Detail

def self.evaluate(name : String, builder, &) #

Runs a scope's body with builder as the receiver of its unqualified calls; a call the builder does not answer goes to the model.


[View source]
def self.expect_no_arguments(name : String, args : Tuple, kwargs : NamedTuple) : Nil #

[View source]

Macro Detail

macro scope(name, scope_proc) #

Define a scope with the given name and query logic

The body runs on the query the scope is called on, as if it were written there: chained after other query methods it adds to them, and Model.name runs it on Model.query. Call the builder's methods (where, order, ...) in it; a bare query is the receiver's CQL::Query, which where changes in place, and a body that starts its own query (Post.query...) replaces the chain.

The body returns either:

  • A QueryBuilder instance (recommended)
  • A CQL::Query instance (will be wrapped in QueryBuilder)

Parameters

  • name: The scope name (identifier)
  • scope_proc: A proc/lambda that defines the query logic

Examples

class Post
  # Simple scope
  scope :published, -> { where(published: true) }

  # Parameterized scope
  scope :by_author, ->(user_id : Int64) { where(user_id: user_id) }

  # Scope with complex logic
  scope :recent_published, ->(days : Int32) {
    where(published: true)
      .where { created_at > days.days.ago }
      .order(created_at: :desc)
  }
end

[View source]