ruby - Const_missing hook isn't fired -
i money patched const_missing methods object , in difference contexts:
auto_loader.rb
%w{../../lib ../../app}.each |path| expanded_path = file.expand_path(path,__file__) $load_path.unshift(expanded_path) unless $load_path.include?(expanded_path) end class object def self.inherited(base) base.extend(class_methods) super end def const_missing(const) puts "loading(in object) %s" % const.to_s path = const.to_s.split('::').compact.map(&:downcase).join('/') require path self.const_get(const) end class << self def const_missing(const) puts "loading(in object class << self) %s" % const.to_s path = const.to_s.split('::').compact.map(&:downcase).join('/') require path self.const_get(const) end end module class_methods class << self def const_missing(const) puts "loading(in class_methods class << self) %s" % const.to_s path = const.to_s.split('::').compact.map(&:downcase).join('/') require path self.const_get(const) end end def const_missing(const) puts "loading(in class_methods) %s" % const.to_s path = const.to_s.split('::').compact.map(&:downcase).join('/') require path self.const_get(const) end end extend class_methods end when run code, see:
nameerror: uninitialized constant const without of puts displayed.
i load code with:
pry -r ./lib/auto_loader.rb the result same.
on other hand, if manually fire const_missing method, see loading(in object) const.
why const_missing hook not fired?
your example not minimal , not run. if try following works without problem. think problem related else.
class object def self.inherited(base) base.extend(class_methods) super end def self.const_missing_impl(const, location) puts "loading(in #{location}) %s" % const.to_s path = const.to_s.split('::').compact.map(&:downcase).join('/') puts "require #{path}" end def const_missing(const) object.const_missing_impl(const, 'object') end class << self def const_missing(const) object.const_missing_impl(const, 'object class << self') end end module class_methods def const_missing(const) object.const_missing_impl(const, 'class_methods') end class << self def const_missing(const) object.const_missing_impl(const, 'class_methods class << self') end end end extend class_methods end = const1 b = a::const2 c = string::const3 d = class_methods::const4 # prints loading(in object class << self) const1 require const1 loading(in object class << self) const2 require const2 loading(in object class << self) const3 require const3 loading(in class_methods class << self) const4 require const4
Comments
Post a Comment