Ruby 如何隐式引用变量

Ruby 如何隐式引用变量,ruby,implicit,receiver,Ruby,Implicit,Receiver,我的代码有很多这样的内容:driver.blahblahblah。考虑下面的代码示例,取自. 如何使驱动程序隐式?例如,有一种方法叫做driver.save\u screenshot()。我想说save_screenshot(“a.png”),因为只有驱动程序变量/对象有这个方法。如果有很多方法的接收者是驱动程序,那么让接收者隐式的方法是: driver.instance_eval do method_1... method_2... ... end 但请注意,这会稍微慢一点。如果

我的代码有很多这样的内容:
driver.blahblahblah
。考虑下面的代码示例,取自.


如何使
驱动程序
隐式?例如,有一种方法叫做
driver.save\u screenshot()
。我想说
save_screenshot(“a.png”)
,因为只有
驱动程序
变量/对象有这个方法。

如果有很多方法的接收者是
驱动程序
,那么让接收者隐式的方法是:

driver.instance_eval do
  method_1...
  method_2...
  ...
end
但请注意,这会稍微慢一点。如果您只是想找到一种懒惰的方法,那么最好的方法就是将局部变量缩短为一个字母,而不要费心使其隐式

d = .... # instead of `drive`
d.method_1...
d.method_2...
...

您可以从ActiveSupport使用
委托
,如下例:

require 'active_support/core_ext/module/delegation'

class MyClass
  delegate :find_element, :save_screenshot, to: :driver

  def foo
    find_element
    save_screenshot
  end

  def driver
    @driver ||= Driver.new
  end
end

class Driver
  def find_element
    puts "find_element"
  end

  def save_screenshot
    puts "save_screenshot"
  end
end

MyClass.new.foo

或者使用(但我不建议这样做)装饰驱动程序。

引用对象并不是重复你自己。重复你自己是指你发现自己在多个地方复制粘贴相似的代码块。你的情况并不清楚。隐式接收器是多个方法中的同一个对象,还是根据方法要求自动查找接收器?为什么
SimpleDelegator
不好?使用SimpleDelegator可以获得整个修饰对象的公共接口,而臃肿的api几乎从来都不是一个好主意。您还必须注意不要覆盖装饰对象所使用的方法。哦,
SimpleDelegator
通常并不坏-我的意思是使用它来解决此类问题不是一个好主意。
require 'active_support/core_ext/module/delegation'

class MyClass
  delegate :find_element, :save_screenshot, to: :driver

  def foo
    find_element
    save_screenshot
  end

  def driver
    @driver ||= Driver.new
  end
end

class Driver
  def find_element
    puts "find_element"
  end

  def save_screenshot
    puts "save_screenshot"
  end
end

MyClass.new.foo