Module: LazyInit::ClassMethods

Defined in:
lib/lazy_init/class_methods.rb

Overview

Provides class-level methods for defining lazy attributes with various optimization strategies.

This module is automatically extended when a class includes or extends LazyInit. It analyzes attribute configuration and selects the most efficient implementation: simple inline methods for basic cases, optimized dependency methods for single dependencies, and full LazyValue wrappers for complex scenarios.

The module generates three methods for each lazy attribute:

  • ‘attribute_name` - the main accessor method

  • ‘attribute_name_computed?` - predicate to check computation state

  • ‘reset_attribute_name!` - method to reset and allow recomputation

Examples:

Basic lazy attribute

class ApiClient
  extend LazyInit

  lazy_attr_reader :connection do
    HTTPClient.new(api_url)
  end
end

Lazy attribute with dependencies

class DatabaseService
  extend LazyInit

  lazy_attr_reader :config do
    load_configuration
  end

  lazy_attr_reader :connection, depends_on: [:config] do
    Database.connect(config.database_url)
  end
end

Since:

  • 0.1.0

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.extended(base) ⇒ void

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.

This method returns an undefined value.

Set up necessary infrastructure when LazyInit is extended by a class.

This is an internal Ruby hook method that’s automatically called when a class extends LazyInit. Users should never call this method directly - it’s part of Ruby’s module extension mechanism.

Initializes thread-safe mutex and dependency resolver for the target class. This ensures each class has its own isolated dependency management.

Parameters:

  • base (Class)

    the class being extended with LazyInit

Since:

  • 0.1.0



52
53
54
55
# File 'lib/lazy_init/class_methods.rb', line 52

def self.extended(base)
  base.instance_variable_set(:@lazy_init_class_mutex, Mutex.new)
  base.instance_variable_set(:@dependency_resolver, DependencyResolver.new(base))
end

Instance Method Details

#dependency_resolverDependencyResolver

Access the dependency resolver for this class.

Handles dependency graph management and resolution order computation. Creates a new resolver if one doesn’t exist.

Returns:

Since:

  • 0.1.0



73
74
75
# File 'lib/lazy_init/class_methods.rb', line 73

def dependency_resolver
  @dependency_resolver ||= DependencyResolver.new(self)
end

#lazy_attr_reader(name, timeout: nil, depends_on: nil, &block) ⇒ void

This method returns an undefined value.

Define a thread-safe lazy-initialized instance attribute.

The attribute will be computed only once per instance when first accessed. Subsequent calls return the cached value. The implementation is automatically optimized based on complexity: simple cases use inline variables, single dependencies use optimized resolution, complex cases use full LazyValue.

Examples:

Simple lazy attribute

lazy_attr_reader :expensive_data do
  fetch_from_external_api
end

With dependencies

lazy_attr_reader :database, depends_on: [:config] do
  Database.connect(config.database_url)
end

With timeout protection

lazy_attr_reader :slow_service, timeout: 10 do
  SlowExternalService.connect
end

Parameters:

  • name (Symbol, String)

    the attribute name

  • timeout (Numeric, nil) (defaults to: nil)

    timeout in seconds for the computation

  • depends_on (Array<Symbol>, Symbol, nil) (defaults to: nil)

    other attributes this depends on

  • block (Proc)

    the computation block

Raises:

Since:

  • 0.1.0



106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
# File 'lib/lazy_init/class_methods.rb', line 106

def lazy_attr_reader(name, timeout: nil, depends_on: nil, &block)
  validate_attribute_name!(name)
  raise ArgumentError, 'Block is required' unless block

  # store configuration for introspection and debugging
  config = {
    block: block,
    timeout: timeout || LazyInit.configuration.default_timeout,
    depends_on: depends_on
  }
  lazy_initializers[name] = config

  # register dependencies with resolver if present
  dependency_resolver.add_dependency(name, depends_on) if depends_on

  # select optimal implementation strategy based on complexity
  if enhanced_simple_case?(timeout, depends_on)
    if simple_dependency_case?(depends_on)
      generate_simple_dependency_method(name, depends_on, block)
    else
      generate_simple_inline_method(name, block)
    end
  else
    generate_complex_lazyvalue_method(name, config)
  end

  # generate helper methods for all implementation types
  generate_predicate_method(name)
  generate_reset_method(name)
end

#lazy_class_variable(name, timeout: nil, depends_on: nil, &block) ⇒ void

This method returns an undefined value.

Define a thread-safe lazy-initialized class variable shared across all instances.

The variable will be computed only once per class when first accessed. All instances share the same computed value. Class variables are always implemented using LazyValue for full thread safety and feature support.

Examples:

Shared connection pool

lazy_class_variable :connection_pool do
  ConnectionPool.new(size: 20)
end

Parameters:

  • name (Symbol, String)

    the class variable name

  • timeout (Numeric, nil) (defaults to: nil)

    timeout in seconds for the computation

  • depends_on (Array<Symbol>, Symbol, nil) (defaults to: nil)

    other attributes this depends on

  • block (Proc)

    the computation block

Raises:

Since:

  • 0.1.0



155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
# File 'lib/lazy_init/class_methods.rb', line 155

def lazy_class_variable(name, timeout: nil, depends_on: nil, &block)
  validate_attribute_name!(name)
  raise ArgumentError, 'Block is required' unless block

  class_variable_name = "@@#{name}_lazy_value"

  # register dependencies for class-level attributes too
  dependency_resolver.add_dependency(name, depends_on) if depends_on

  # cache configuration for use in generated methods
  cached_timeout = timeout
  cached_depends_on = depends_on
  cached_block = block

  # generate class-level accessor with full thread safety
  define_singleton_method(name) do
    @lazy_init_class_mutex.synchronize do
      return class_variable_get(class_variable_name).value if class_variable_defined?(class_variable_name)

      # resolve dependencies using temporary instance if needed
      if cached_depends_on
        temp_instance = begin
          new
        rescue StandardError
          # fallback for classes that can't be instantiated normally
          Object.new.tap { |obj| obj.extend(self) }
        end
        dependency_resolver.resolve_dependencies(name, temp_instance)
      end

      # create and store the lazy value wrapper
      lazy_value = LazyValue.new(timeout: cached_timeout, &cached_block)
      class_variable_set(class_variable_name, lazy_value)
      lazy_value.value
    end
  end

  # generate class-level predicate method
  define_singleton_method("#{name}_computed?") do
    if class_variable_defined?(class_variable_name)
      class_variable_get(class_variable_name).computed?
    else
      false
    end
  end

  # generate class-level reset method
  define_singleton_method("reset_#{name}!") do
    if class_variable_defined?(class_variable_name)
      lazy_value = class_variable_get(class_variable_name)
      lazy_value.reset!
      remove_class_variable(class_variable_name)
    end
  end

  # generate instance-level delegation methods for convenience
  define_method(name) { self.class.send(name) }
  define_method("#{name}_computed?") { self.class.send("#{name}_computed?") }
  define_method("reset_#{name}!") { self.class.send("reset_#{name}!") }
end

#lazy_initializersHash<Symbol, Hash>

Access the registry of all lazy initializers defined on this class.

Used internally for introspection and debugging. Each entry contains the configuration (block, timeout, dependencies) for a lazy attribute.

Returns:

  • (Hash<Symbol, Hash>)

    mapping of attribute names to their configuration

Since:

  • 0.1.0



63
64
65
# File 'lib/lazy_init/class_methods.rb', line 63

def lazy_initializers
  @lazy_initializers ||= {}
end