从BasicObject继承以提高性能

时间:2018-06-20 17:57:47

标签: ruby

我正在研究是否可以通过使PageObjects类继承自BasicObject来提高性能。理由是BasicObjects的内置方法比常规对象少得多。但是,我遇到了此错误:

 <class:PageObject>': uninitialized constant PageObject::ENV (NameError)
 Did you mean?  ENV

我尝试了多种导入env.rb的方法(BasicObject没有内置的方法),但是我一直遇到错误。这是导入它的一种尝试。

 class PageObject < BasicObject
   include ENV
   def initialize
     home_dir = ENV["HOME"]
     load_page_object_file(open("# 
    {home_dir}/code/automate_shared/lib/shared_page_objects.yml"))
    load_page_object_file(open("#{home_dir}/code/automate_shared/lib/urls.yml"))
    load_page_object_file('spec/support/page_objects.yml')
   end
 end

如何从rubystubs库导入类方法?

1 个答案:

答案 0 :(得分:1)

我不确定使用BasicObject可以解决哪些性能目标,但这是Object中可用的 instance方法,而在BasicObject中则不可用Object.instance_methods - BasicObject.instance_methods #=> [:instance_of?, :kind_of?, :is_a?, :tap, :public_send, :method, :public_method, :singleton_method, :remove_instance_variable, :define_singleton_method, :instance_variable_set, :extend, :to_enum, :enum_for, :<=>, :===, :=~, :!~, :eql?, :respond_to?, :freeze, :inspect, :object_id, :send, :display, :to_s, :nil?, :hash, :class, :singleton_class, :clone, :dup, :itself, :taint, :tainted?, :untaint, :untrust, :untrusted?, :trust, :frozen?, :methods, :singleton_methods, :protected_methods, :private_methods, :public_methods, :instance_variable_get, :instance_variables, :instance_variable_defined?]

Object

由于您希望使用BasicObject中的方法很少,因此可以不用创建class MyBasicObject instance_methods.each do |m| next if [:instance_of?, :is_a?].include?(m) undef_method m end end class PageObject < MyBasicObject def initialize home_dir = ::ENV["HOME"] load_page_object_file(open("# {home_dir}/code/automate_shared/lib/shared_page_objects.yml")) load_page_object_file(open("#{home_dir}/code/automate_shared/lib/urls.yml")) load_page_object_file('spec/support/page_objects.yml') end end 而创建新的类,并取消定义不需要的方法。

open

但是,如果您的目标只是使open工作,请注意KernelObject模块的方法,而不是BasicObject的实例方法。您可以通过在类中include显式设置Kernel模块来简化 class PageObject < BasicObject include ::Kernel def initialize home_dir = ::ENV["HOME"] load_page_object_file(open("# {home_dir}/code/automate_shared/lib/shared_page_objects.yml")) load_page_object_file(open("#{home_dir}/code/automate_shared/lib/urls.yml")) load_page_object_file('spec/support/page_objects.yml') end end 的特殊情况。

::ENV

PS:感谢@anthony指出正确使用/\.\d{0,}/g