[英]Using const_missing to refer to a class external from the module
我有一個具有以下文件夾結構的應用程序:
# /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
下定義的所有類(根本不需要它們)。
我如何獲得這個?
如果該類存在於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"
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.