动态创建没有命名空间的类
我正在尝试使用 eval 方法动态创建一个类。除了一个小问题外,它运行良好。正如我的代码所示,我正在 BrowserFactory 类中创建 Browser 类。当我这样做时,Browser 类添加了一个 BrowserFactory 命名空间。无论如何,是否可以在不附加 BrowserFactory 命名空间的情况下从字符串评估 Browser 类?
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
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
定义浏览器(或 ::Browser,直接回答您的问题)将阻止您多次调用工厂。
我建议使用匿名类。不需要 eval,顺便说一句,如果您愿意,您可以定义类方法 to_s:
Defining Browser (or ::Browser, to directly answer your question) will prevent you from calling your factory more than once.
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:
更改
为
Change
to
这是一个小测试套件:
Here's a small testsuite: