2010-11-16 53 views
3

当我的系统需要两个同名的类或模块时,我能做些什么来指定我的意思?Ruby:导入两个相同名称的模块

我正在使用rails(新增功能),并且我的一个模型被命名为“Thread”。当我尝试引用thread_controller.rb中的“Thread”类时,系统会返回一些其他具有相同名称的常量。

<thread.rb> 
class Thread < ActiveRecord::Base 

    def self.some_class_method 
    end 

end 

<thread_controller.rb> 
class ThreadController < ApplicationController 

    def index 
    require '../models/thread.rb' 
    @threads = Thread.find :all 
    end 

end 

当我尝试使用Thread.find()时,我得到一个错误,表示Thread没有名为find的方法。当我访问Thread.methods时,我没有发现我的some_class_method方法。

任何帮助? (并且不要打扰张贴“只是命名你的模型别的东西”。指出明显的妥协是没有帮助的。)

回答

2

您可以将您的应用放入自己的名称空间。

<my_app/thread.rb> 
module MyApp 
    class Thread 
    end 
end 
2

没有,真的,请为你的模型命名。

Thread是Ruby中的一个保留常量,并且重写该常量只会让你遇到麻烦。我妥协了my application,并将其改为Topic

+0

好的。这比通常的“改变你的名字”的回应要好。谢谢。 ...但是,我想知道一个更一般的答案,在不处理保留常量重复的情况下可以使用这个答案。 – JellicleCat 2010-11-16 03:14:38

2

如果你绝对必须覆盖现有的常量,你可以做这样的事情:

# use Object to make sure Thread is overwritten globally 
# use `send` because `remove_const` is a private method of Object 
# Can use OldThread to access already existing Thread 
OldThread = Object.send(:remove_const, :Thread) 

# define whatever you want here 
class MyNewThread 
    ... 
end 

# Now Thread is the same as MyNewThread 
Object.send(:const_set, :Thread, MyNewThread) 

显然,任何在预先存在的Thread会被打掉依赖,除非你做了某种猴子打补丁的。

只因为这种事情可以做到,并不代表它应该是。但在某些情况下,它可以很方便,例如在测试中,您可以用自己的“哑”对象覆盖远程数据源。

相关问题