Ruby 部分覆盖父 class 方法

Ruby partically override parent class method

如何覆盖 ruby 父 class 中的一行或多行代码? 例如:我有 Rails 控制器 class 方法 create:

class GenericController < ApplicationController
def create
    @resource = SomeClass.new
    if @resource.save
      ...
    else
      ...
    end
  end
end

我还有另一个控制器,这个控制器的子控制器

class ChildController < GenericController
  def create
    super do
      # HERE I WANT TO DO SOME ACTIONS BEFORE SAVE.
    end
  end
end

我怎样才能做到这一点?我试过这个(通用控制器):

def create
    @resource = SomeClass.new
    yield if block_given?
    if @resource.save
      ...
    end
  end

但是如果我想通过一个以上的街区怎么办?例如,如果我想进行回调:after_init、:before_save、:after_save 等等?

  def create
    super do
      # HERE I WANT TO DO SOME ACTIONS BEFORE SAVE.
    end
  end

But what if I want to pass more than one block? For example if I want to make callbacks :after_init, :before_save, :after_save and so on

您需要将块传递给超类方法您的create()方法之外:

class Dog < GenericController
  before_save do
    puts 'before1'
  end

  after_save do
    puts 'after1'
  end

  before_save do
    puts 'before2'
  end

  def create
    super
  end

end

class GenericController
  class <<self
    attr_accessor :before, :after

    def before_save(&block)
      @before << block
    end

    def after_save(&block)
      @after << block
    end
  end

  def self.inherited(subclass)
    subclass.instance_variable_set(:@before, [])
    subclass.instance_variable_set(:@after, [])
  end

  def create

    self.class.before.each do |proc|
      proc.call
    end

    puts 'saving resource...'
    #@resource.save

    self.class.after.each do |proc|
      proc.call
    end

  end

end

Dog.new.create

--output:--
before1
before2
saving resource...
after1