0

我有一个具有此文件夹结构的应用程序:

# /app/controllers/first_controller.
class FirstController
  def method
    'External'
  end
end

# /app/controllers/second_controller.rb
class SecondController
  def method
    'External'
  end
end

# /app/controllers/foo/first_controller.rb
module Foo
  class FirstController < ::FirstController
    def method
      'Internal'
    end
  end
end

我想要的行为是:

Foo::FirstController#method => "Internal"

Foo::SecondController#method => "External"

因此,如果控制器没有在模块中定义Foo,它应该实例化外部 cass

我尝试创建一个文件foo.rb

# /app/controllers/foo.rb
module Foo
  def self.const_missing(name)
    "::#{name}".constantize
  end
end

但是使用它会使rails忽略下定义的所有类/app/controllers/foo/*.rb(根本不需要它们)。

我怎样才能得到这个?

4

1 回答 1

1

如果类存在于命名空间中,就让 Rails 来完成这项工作Foo。它也用于const_missing解析类名:

module Foo
  def self.const_missing(name)
    if File.exists?("app/controllers/foo/#{name.to_s.underscore}.rb")
      super
    else
      "::#{name}".constantize
    end
  end
end

输出:

Foo::FirstController.new.method
# => "Internal" 
Foo::SecondController.new.method
# => "External" 
于 2015-04-02T11:24:21.357 回答