Module: LazyInit::ClassMethods

Defined in:
lib/lazy_init/class_methods.rb

Overview

Class-level methods for defining lazy attributes with Ruby version-specific optimizations.

Automatically selects the most efficient implementation:

  • Ruby 3+: eval-based methods for maximum performance
  • Ruby 2.6+: define_method with full compatibility
  • Simple cases: inline variables, dependency cases: lightweight resolution
  • Complex cases: full LazyValue with timeout and dependency support

Examples:

Basic lazy attribute

class ApiClient
  extend LazyInit

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

With dependencies

lazy_attr_reader :database, depends_on: [:config] do
  Database.connect(config.database_url)
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.

Parameters:

  • base (Class)

    the class being extended with LazyInit

Since:

  • 0.1.0



33
34
35
# File 'lib/lazy_init/class_methods.rb', line 33

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

Instance Method Details

#dependency_resolverDependencyResolver

Lazy dependency resolver - created only when needed for performance.

Returns:

Since:

  • 0.1.0



47
48
49
# File 'lib/lazy_init/class_methods.rb', line 47

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.

Automatically optimizes based on Ruby version and complexity:

  • Ruby 3+: uses eval for maximum performance
  • Simple cases: direct instance variables
  • Dependencies: lightweight resolution for single deps, full resolver for complex
  • Timeouts: full LazyValue wrapper

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



81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
# File 'lib/lazy_init/class_methods.rb', line 81

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
  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
  if depends_on && Array(depends_on).size == 1 && !timeout
    generate_simple_dependency_with_inline_check(name, Array(depends_on).first, block)
    generate_predicate_method(name)
    generate_reset_method(name)
  elsif depends_on && Array(depends_on).size > 1 && !timeout
    generate_fast_dependency_method(name, depends_on, block, config)
    generate_predicate_method(name)
    generate_reset_method_with_deps_flag(name)
  elsif simple_case_eligible?(timeout, depends_on)
    generate_optimized_simple_method(name, block)
  elsif enhanced_simple_case?(timeout, depends_on)
    if simple_dependency_case?(depends_on)
      generate_lazy_compiling_method(name, block, :dependency, depends_on)
    else
      generate_lazy_compiling_method(name, block, :simple, nil)
    end
    generate_predicate_method(name)
    generate_reset_method(name)
  else
    generate_complex_lazyvalue_method(name, config)
    generate_predicate_method(name)
    generate_reset_method(name)
  end
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.

Uses full LazyValue wrapper for thread safety and feature completeness. All instances share the same computed value.

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



139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
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
# File 'lib/lazy_init/class_methods.rb', line 139

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
  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>

Registry of all lazy initializers defined on this class.

Returns:

  • (Hash<Symbol, Hash>)

    mapping of attribute names to their configuration

Since:

  • 0.1.0



40
41
42
# File 'lib/lazy_init/class_methods.rb', line 40

def lazy_initializers
  @lazy_initializers ||= {}
end