动态创建没有名称空间的类 [英] dynamically create a class without a namespace
问题描述
我正在尝试使用eval方法动态创建一个类.除了一个小问题,它工作正常.如我的代码所示,我正在BrowserFactory类内创建Browser类.当我这样做时,Browser类具有添加的BrowserFactory命名空间.无论如何,在没有附加BrowserFactory命名空间的情况下,是否可以通过字符串评估Browser类?
I am trying to dynamically create a class using the eval method. It is working fine except for one small problem. As my code shows I am creating the Browser class inside the BrowserFactory class. When I do this the Browser class has an added namespace of BrowserFactory. Is there anyway to evaluate the Browser class from a string without the BrowserFactory namespace being attached?
class BrowserFactory
def self.create_browser(browser)
super_class = nil
case browser
when 'IE'
require 'watir'
super_class = 'Watir::IE'
when 'celerity'
require 'celerity'
super_class = 'Celerity::Browser'
end
raise StandardError.new("Browser '#{browser}' is not currentlys supported") if super_class.nil?
eval <<EOS
class Browser < #{super_class}
include Singleton
include BrowserModification
end
EOS
return Browser.instance
end
end
推荐答案
定义浏览器(或:: Browser,直接回答您的问题)将阻止您多次致电工厂.
Defining Browser (or ::Browser, to directly answer your question) will prevent you from calling your factory more than once.
我建议使用匿名类.不需要eval,顺便说一句,如果需要,您可以将类方法定义为to_s:
I would recommend to use an anonymous class. No need for eval, btw, and you can define the class method to_s if you want to:
class BrowserFactory
def self.create_browser(browser)
super_class = case browser
when 'IE'
require 'watir'
Watir::IE
when 'celerity'
require 'celerity'
Celerity::Browser
else
raise StandardError.new("Browser '#{browser}' is not currentlys supported")
end
klass = Class.new(super_class) do
include Singleton
include BrowserModification
def self.to_s
"Modified#{superclass}"
end
end
klass.instance
end
end
这篇关于动态创建没有名称空间的类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!