Module: Servus::Extensions::Lazily::Call

Defined in:
lib/servus/extensions/lazily/call.rb

Overview

Provides lazy record resolution for service inputs.

This module extends Base with the #lazily class method, enabling services to accept either a record ID or an already-loaded record instance. Resolution happens lazily on first access and is memoized.

See Also:

  • Lazily#lazily

Instance Method Summary collapse

Instance Method Details

#lazily(name, finds:, by: :id) ⇒ void

Note:

Only available when ActiveRecord is loaded (via Railtie)

This method returns an undefined value.

Declares a lazy record resolver for a service input.

Defines an accessor method that lazily resolves the input value to a record. If the value is already an instance of the target class, it is returned directly. If the value is an ID (or other lookup value), it is resolved via the target class’s .find or .find_by! method. Arrays are resolved via .where.

The resolved record is written back to the instance variable, so subsequent calls return the same object without re-querying.

Examples:

Basic usage with .find

lazily :user, finds: User
# user: 123       → User.find(123)
# user: user_inst → returns user_inst directly

Custom column lookup

lazily :account, finds: Account, by: :uuid
# account: "abc-def" → Account.find_by!(uuid: "abc-def")

Array input

lazily :users, finds: User
# users: [1, 2, 3] → User.where(id: [1, 2, 3])

Parameters:

  • name (Symbol)

    the param/ivar name, also becomes the accessor method

  • finds (Class)

    the model class to resolve against (e.g., User, Account)

  • by (Symbol) (defaults to: :id)

    the lookup column (default: :id). When :id, uses .find. Otherwise uses .find_by!(column: value).

See Also:



45
46
47
48
# File 'lib/servus/extensions/lazily/call.rb', line 45

def lazily(name, finds:, by: :id)
  (@lazy_resolvers ||= {})[name] = { klass: finds, by: by }
  define_resolver_method(name, finds, by)
end

#lazy_resolversHash{Symbol => Hash}

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

Returns the hash of registered lazy resolvers for this service class.

Returns:

  • (Hash{Symbol => Hash})

    resolver configurations keyed by name



54
55
56
# File 'lib/servus/extensions/lazily/call.rb', line 54

def lazy_resolvers
  @lazy_resolvers || {}
end