如何在另一个方法完成执行之前调用私有方法?

时间:2017-11-09 08:41:23

标签: ruby-on-rails ruby callback

我在rails中有两种方法

def foo
    puts "foo"
    find_article
end

def bar
    puts "bar"
    find_article
end

private
def find_article
    do_something
end

有没有办法调用find_article而无需在foobar中指定?

3 个答案:

答案 0 :(得分:1)

Rails包含了一种使用ActiveModel::Callbacks执行此操作的方法 http://api.rubyonrails.org/classes/ActiveModel/Callbacks.html

class FooBar
  extend ActiveModel::Callbacks
  define_model_callbacks :foobar
  after_foobar :find_article

  def foo
    run_callbacks :foobar do
      puts "foo"
    end
  end

  def bar
    run_callbacks :foobar do
      puts "bar"
    end
  end

  private

  def find_article
    puts 'finding article'
  end
end

结果:

[1] pry(main)> FooBar.new.foo
foo
finding article
=> nil
[2] pry(main)> FooBar.new.bar
bar
finding article
=> nil

答案 1 :(得分:0)

以下内容:

module Magic
  def after_method(original, callback)
    all = [*original]
    all.each do |original|
      m = instance_method(original)
      define_method(original) do |*args, &block|
        m.bind(self).(*args, &block)
        send(callback)
      end
    end
  end
end


class X
  extend Magic
  def foo
    puts "foo"
  end

  def bar
    puts "bar"
  end

  private
  def find_article
    puts "DONE"
  end

  after_method [:foo, :bar], :find_article    
end
X.new.foo
# foo
# done

here

的帮助很少

答案 2 :(得分:0)

如果这是Rails,那么after_action

class MyController
  after_action :find_article

  def foo
    puts "foo"
  end

  def bar
    puts "bar"
  end

  private

  def find_article
    do_something
  end
end