I’m working on a gem for a RESTful API, and I noticed that, since it’s a REST api, a lot of the resource urls are the same, and thus a few methods for each class would be the exact same (just the uri path differing).
I started out creating classes like this:
module NameSpace
Class1 < SuperClass; ... end
end
in various files, would be similarly:
moduel NameSpace
Class2 < SuperClass; ... end
end
So, here is what I’ve developed so far:
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
But when I try to run the console, and require my gem, I get this output:
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
and when I try to do
> NameSpace::Cass1, I get
NameError: uninitialized constant NameSpace::Class1
My question is: am I close? How do I properly define dynamic subclassed and namespaced classes?
Setting the CONTROLLER constant using const_set seems to work:
For the other problem, you should change
Object.const_set(to justconst_set(, which will set the constant in your NameSpace module the way you want it.