Module: LazyConst

Defined in:
lib/lazy_const.rb

Constant Summary collapse

CACHE =
{}

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.clearObject



25
26
27
28
29
# File 'lib/lazy_const.rb', line 25

def self.clear
  LazyConst::CACHE.keys.each do |k|
    LazyConst::CACHE[k] = nil
  end
end

.preloadObject



17
18
19
20
21
22
23
# File 'lib/lazy_const.rb', line 17

def self.preload
  self.clear
  LazyConst::CACHE.keys.each do |class_dot_name|
    klass, name = class_dot_name.split('.')
    m = const_get(klass.to_sym).send name.to_sym
  end
end

Instance Method Details

#lazy_const(name, &block) ⇒ Object



9
10
11
12
13
14
15
# File 'lib/lazy_const.rb', line 9

def lazy_const(name, &block)
  raise Error("lazy_const requires a block") unless block_given?
  LazyConst::CACHE["#{self.name}.#{name}"] = nil
  meta_class.send(:define_method, name) do
    LazyConst::CACHE["#{self.name}.#{name}"] ||= block.call
  end
end

#meta_classObject



5
6
7
# File 'lib/lazy_const.rb', line 5

def meta_class
  @meta_class ||= class << self; self end
end