在Rails中执行类似before_filter的方法

hyp*_*pee 3 ruby metaprogramming

我试着在'master'方法之前编写一个元编程来执行一个方法.为什么?因为,我有几个课,重复呼叫的头部很难看method

案件 :

class MyClass
  include MySuperModule
  before :method, call: before_method

  def before_method
    puts "Before.."
  end
end

class SomeClass < MyClass
  def method
    puts "Method.."
  end
end

module MySuperModule
  # the awesome code
end
Run Code Online (Sandbox Code Playgroud)

输出:

SomeClass.new.method => "Before.. Method.."
Run Code Online (Sandbox Code Playgroud)

所以,我尝试编写一个有ClassMethods或method_missing没有成功的模块.

Max*_*Max 5

你不需要像这样的简单元编程的宝石.您可以做的是重新定义"after"方法以调用"before"方法,然后调用原始的"after"方法.

即使在before同一方法上多次使用或创建一系列before调用时,这也可以工作.

module MySuperModule
  def before meth, opts
    old_method = instance_method(meth)
    define_method(meth) do
      send opts[:call]
      old_method.bind(self).call
    end
  end
end

class MyClass
  extend MySuperModule

  def foo
    puts "foo"
  end

  def bar
    puts "bar"
  end

  def baz
    puts "baz"
  end

  before :foo, call: :bar
  before :bar, call: :baz
end

MyClass.new.foo
# baz
# bar
# foo
Run Code Online (Sandbox Code Playgroud)