ruby-on-rails - 在多个方法中添加相同的代码
问题描述
我有一个有 N 个方法的类。
class MyClass
def self.method_one(params)
#specific code
end
def self.method_two(params)
#specific code
end
end
我需要为该类中创建的每个方法添加相同的代码。我需要将代码放在“开始和救援”之间
我尝试了以下方法,但没有成功:
class MyClass < BaseClass
add_rescue :method_one, :method_two, Exception do |message|
raise message
end
def self.method_one(params)
#specific code
end
def self.method_two(params)
#specific code
end
end
我创建了一个方法来改变方法
class BaseClass
def self.add_rescue(*meths, exception, &handler)
meths.each do |meth|
old = instance_method(meth)
define_method(meth) do |*args|
begin
old.bind(self).call(*args)
rescue exception => e
handler.call(e)
end
end
end
end
end
我总是收到错误消息:未定义的方法 `method_one 'for Myclass: Class
解决方案
MyClass#method_one
是一个类方法,或者换句话说,是 的实例方法MyClass.singleton_class
。也就是说,我们可以Module#prepend
将所需的功能MyClass.singleton_class
:
def self.add_rescue(*meths, exception, &handler)
mod =
Module.new do
meths.each do |meth|
define_method meth do |*args, &λ|
begin
super(*args, &λ)
rescue exception => e
handler.(e)
end
end
end
end
MyClass.singleton_class.prepend(mod)
end
推荐阅读
- php - 为什么在php中通过dompdf将html转换为pdf时,某些单词被压缩并且单词之间的空格被删除
- ruby-on-rails - 无法在 Rails 6 中创建或构建嵌套模型
- vue.js - 为什么过渡组动画不透明度但不动画高度?
- date - 所需的二进制日期规范
- ajax - 在 WordPress 上编写 AJAX 点击计数器
- ruby-on-rails - ajax请求部分中的非空查询非常慢
- tensorflow - 计算两个 RGB 点云之间的差异
- python - 试图获取事件 channel_name_change
- forms - 我可以按分隔符拆分并在 SharePoint 列表中创建新行吗?
- javascript - JavaScript 或 jQuery 中的 HTML 表单验证逻辑