使用类<<自动加载类在Rails中自我

时间:2014-01-14 14:06:57

标签: ruby ruby-on-rails-4 metaprogramming

我有以下3个文件:

test.rb

# doesn't work, raises error: NameError: uninitialized constant Baz
Foo::Bar.do_stuff_1

# does work
Foo::Bar.do_stuff_2

# does work
Foo::Bar.new.do_stuff_3

bar.rb

module Foo   
  class Bar    
    class << self    
      def do_stuff_1

        puts "class level: #{Baz.new.class}"

      end    
    end

    def self.do_stuff_2

      puts "class level: #{Baz.new.class}"

    end

    def do_stuff_3

      puts "Instance level: #{Baz.new.class}"

    end    
  end    
end

baz.rb

module Foo    
  class Baz   
    def initialize

    end    
  end    
end

do_stuff_1方法引发异常, NameError:未初始化的常量Baz ,而其他方法正常执行。我认为它与class << self ... end调整元类和def self.method ... end调整类本身有关。

我想知道是否有办法让class << self ... enddef self.method ... end一样适当地自动加载Baz类。

我正在使用Rails 4.0.2,Ruby 2.0.0,我正在使用application.rb自动加载类。

1 个答案:

答案 0 :(得分:0)

这本身不是自动加载问题,而是名称范围问题。对于第一种方法,您使用Bar的单例类,因此您需要将Baz引用为Foo::Baz

如果您想在不使用名称Foo::Baz的情况下从该上下文引用Foo,则可以使用在该上下文中评估为Foo的任何表达式,例如Module.nesting[2],如:

puts "class level: #{Module.nesting[2]::Baz.new.class}"}