我正在为 RESTful API 开发一个 gem,我注意到,因为它是一个 REST api,所以很多资源 url 是相同的,因此每个类的一些方法是完全相同的(只是 uri路径不同)。
我开始创建这样的类:
module NameSpace
Class1 < SuperClass; ... end
end
在各种文件中,将类似:
moduel NameSpace
Class2 < SuperClass; ... end
end
所以,这是我迄今为止开发的:
RESOURCE_NAMES = [
"Class1",
"Class2",
...
]
module NameSpace
RESOURCE_NAMES.each {|class_name|
Object.const_set(
class_name,
Class.new(SuperClass) do
CONTROLLER = class_name.downcase
@attributes = {}
# class variables
def self.show(id); ... end
def self.update(id); ... end
def self.destroy(id); ... end
end
)
}
end
但是当我尝试运行控制台并需要我的 gem 时,我得到了以下输出:
require "rubygems"
require "mygem"
/home/me/.rvm/gems/ruby-1.8.7-p371/gems/mygem-0.0.1/lib/mygem/restful_resource.rb:17: warning: already initialized constant CONTROLLER
/home/me/.rvm/gems/ruby-1.8.7-p371/gems/mygem-0.0.1/lib/mygem/restful_resource.rb:17: warning: already initialized constant CONTROLLER
/home/me/.rvm/gems/ruby-1.8.7-p371/gems/mygem-0.0.1/lib/mygem/restful_resource.rb:17: warning: already initialized constant CONTROLLER
/home/me/.rvm/gems/ruby-1.8.7-p371/gems/mygem-0.0.1/lib/mygem/restful_resource.rb:17: warning: already initialized constant CONTROLLER
/home/me/.rvm/gems/ruby-1.8.7-p371/gems/mygem-0.0.1/lib/mygem/restful_resource.rb:17: warning: already initialized constant CONTROLLER
当我尝试做时
> NameSpace::Cass1
,我得到
NameError: uninitialized constant NameSpace::Class1
我的问题是:我接近了吗?如何正确定义动态子类和命名空间类?