ruby - 模块内的回调
问题描述
我有类似的东西:
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
还有其他干净的方法吗?
解决方案
我不确定,但我想你可以使用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"
推荐阅读
- python - Pandas - 将多个数据帧压缩到一个 zip 文件夹
- twilio - 修改正在进行的 Twilio 呼叫会导致断开连接
- firebase - Firebase:在作为地图推送时在文档本身中存储文档 ID
- python - django.core.exceptions.ImproperlyConfigured:包含的 URLconf 中似乎没有任何模式
- r - 如何手动订购 UpsetR 的设置大小条形图
- python - 我在使用 cnn 对超过 10000 个类别进行分类时遇到问题。我该如何解决?
- c# - 使用 List C# 中的 MultipartFormDataContent 发布文件数据
- reactjs - 如何在反应 js 中使用 axios 在 api 中发送正文为空的标头?
- php - 谷歌折线图添加货币符号
- c# - 如何对我的结构接收到的 xml 响应进行类型转换(迭代)