在 Ruby 中,围绕子方法执行块的最佳方法是什么?

jay*_*qui 3 ruby inheritance

我有一个父类:

class Base
  def my_method
    block_method do
      # EXECUTE WHATEVER'S IN THE CHILD VERSION OF my_method
      # HOW TO DO?
    end
  end

  def block_method
    original_foo = 'foo'
    foo = 'CUSTOM FOO'

    yield

    foo = original_foo
  end
end
Run Code Online (Sandbox Code Playgroud)

以及一些儿童课程——目前有五个,还会有更多:

class ChildA < Base
  def my_method
    puts 'apple'
    puts 'aardvark'
  end
end

class ChildE < Base
  def my_method
    puts 'eel'
    puts 'elephant'
  end
end
Run Code Online (Sandbox Code Playgroud)

我想更改变量在每个 的持续时间内所指的Child内容#my_method

Child我的想法是通过将每个的功能包装在一个块中来做到这一点#my_method。但我宁愿在父类中这样做,而不是将每个子类包装#my_method在完全相同的块中。

关于我如何做到这一点有什么见解吗?

如果有一些相反的情况super,我想这将是完成我想做的事情的一种方法。

eng*_*nky 5

您可以使用模块来表达您所说的“与超级相反的东西”,prepend如下所示:

module MethodThing
  # added to remove binding from class since 
  # #my_method relies on the existence of #foo and #foo=
  def self.prepended(base)
    base.attr_reader(:foo) unless base.method_defined?(:foo)
    base.attr_writer(:foo) unless base.method_defined?(:foo=)
  end
  def my_method
    puts "Before: #{foo}"
    original_foo = foo
    self.foo= 'CUSTOM FOO'
    begin
      super
    rescue NoMethodError
      warn "(skipped) #{self.class}##{__method__} not defined"
    end
    self.foo = original_foo
    puts "After: #{foo}"
  end
end
Run Code Online (Sandbox Code Playgroud)

在继承前添加模块

class Base 
  def self.inherited(child)
    child.prepend(MethodThing)
  end

  attr_accessor :foo 
  def initialize
    @foo = 12
  end
end


class ChildA < Base
  def my_method
      puts 'apple'
      puts "During: #{foo}"
      puts 'aardvark'
  end
end

class ChildE < Base
end
Run Code Online (Sandbox Code Playgroud)

输出:

ChildA.new.my_method
# Before: 12
# apple
# During: CUSTOM FOO
# aardvark
# After: 12
ChildE.new.my_method
# Before: 12
# (skipped) ChildE#my_method not defined
# After: 12
Run Code Online (Sandbox Code Playgroud)

还有其他奇怪的方法可以通过继承来实现这一点,例如

class Base
 class << self
   attr_accessor :delegate_my_method
   def method_added(method_name)
     if method_name.to_s == "my_method" && self.name != "Base"
       warn "#{self.name}#my_method has been overwritten use delegate_my_method instead" 
     end
   end
 end
 attr_accessor :foo       

 def my_method
   puts "Before: #{foo}"
    original_foo = foo
    self.foo= 'CUSTOM FOO'
    begin
      method(self.class.delegate_my_method.to_s).()
    rescue NameError, TypeError
      warn "(skipped) #{self.class} method delegation not defined"
    end
    self.foo = original_foo
    puts "After: #{foo}"
 end
end

class ChildA < Base
  self.delegate_my_method = :delegation_method

  def delegation_method
    puts 'apple'
    puts "During: #{foo}"
    puts 'aardvark'
  end
end 
Run Code Online (Sandbox Code Playgroud)

我可能会继续用越来越陌生的方法来解决这个问题,但我认为这些方法会让你到达你需要去的地方。