首页 > 解决方案 > 模块内的回调

问题描述

我有类似的东西:

Module A
    Class A
        def initialize
        end

        def m1
        end

        def m2
        end

        def m3
        end
    end
end

我想要的是在执行 m1、m2 或 m3 之前运行验证,例如 before_action,如果满足条件则返回 nil,例如,如果变量为 nil,则立即返回 nil。

我知道我可以创建一个模块:

module Callbacks
  def callbacks
    @callbacks ||= Hash.new { |hash, key| hash[key] = [] }
  end

  def before_run(method_name, callback)
    callbacks[method_name] << callback
  end

  module InstanceMethods
    def run_callbacks_for(method_name)
      self.class.callbacks[method_name].to_a.each do |callback|
        send(callback)
      end
    end
  end
end

在 A 类内部,我可以调用:

before_run :m1, :my_validation_method
before_run :m2, :my_validation_method
before_run :m3, :my_validation_method

还有其他干净的方法吗?

标签: rubyruby-on-rails-3

解决方案


我不确定,但我想你可以使用prepend 例如:

module Baz
  def foo
    return nil if @a == 0
    super
  end
end

class Foo
  prepend Baz
  def initialize(a)
    @a = a
  end

  def foo
    p 'foo'
  end
end

用户喜欢

Foo.new(0).foo
=> nil

Foo.new(1).foo
"foo"
=> "foo"

推荐阅读