【问题标题】:Using const_missing to refer to a class external from the module使用 const_missing 来引用模块外部的类
【发布时间】:2015-06-07 06:45:03
【问题描述】:

我有一个具有这种文件夹结构的应用:

# /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下定义的所有类(根本不需要它们)。

我怎样才能得到这个?

【问题讨论】:

    标签: ruby-on-rails ruby inheritance class-constants


    【解决方案1】:

    如果类存在于Foo 命名空间中,就让Rails 来完成这项工作。它也使用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" 
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-04-05
      • 1970-01-01
      • 2015-08-11
      相关资源
      最近更新 更多