Ruby部分覆盖父类方法

时间:2015-11-21 11:38:04

标签: ruby-on-rails ruby class inheritance yield

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

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等等?

1 个答案:

答案 0 :(得分:1)

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

但是,如果我想传递多个块怎么办?例如,如果我想   进行回调:after_init,:before_save,:after_save等等

您需要将块传递给超出类 <{1>}方法的超类方法:

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