Class: Module

Inherits:
Object show all
Defined in:
lib/epitools/minimal.rb,
lib/epitools/core_ext/module.rb

Overview

Patch ‘Module#const_missing’ to support ‘autoreq’ (which can autoload gems)

Constant Summary collapse

@@autoreq_is_searching_for =
nil

Instance Method Summary collapse

Instance Method Details

#autoreqsObject



212
213
214
# File 'lib/epitools/minimal.rb', line 212

def autoreqs
  @@autoreqs ||= {}
end

#const_missing(const) ⇒ Object



194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
# File 'lib/epitools/minimal.rb', line 194

def const_missing(const)
  return if const == @@autoreq_is_searching_for

  if thing = autoreqs[const]
    case thing
    when String, Symbol
      require thing
    when Proc
      Object.class_eval(&thing)
    else
      raise "Error: Don't know how to autoload a #{thing.class}: #{thing.inspect}"
    end
  end

  @@autoreq_is_searching_for = const
  const_get(const) || const_missing_without_autoreq(const)
end

#const_missing_without_autoreqObject



192
# File 'lib/epitools/minimal.rb', line 192

alias const_missing_without_autoreq const_missing

#memoize(*methods) ⇒ Object

Cache (memoize) the result of an instance method the first time it’s called, storing this value in the “@_memoized#methodname_cache” instance variable, and always return this value on subsequent calls (unless the returned value is nil).



9
10
11
12
13
14
15
16
17
18
19
20
# File 'lib/epitools/core_ext/module.rb', line 9

def memoize(*methods)
  # alias_method is faster than define_method + old.bind(self).call
  methods.each do |meth|
    alias_method "__memoized__#{meth}", meth
    module_eval <<-EOF
      def #{meth}(*a, &b)
        # assumes the block won't change the result if the args are the same
        (@__memoized_#{meth}_cache ||= {})[a] ||= __memoized__#{meth}(*a, &b)
      end
    EOF
  end
end