在多个方法中添加相同的代码
add the same code in multiple methods
我有一个 class 有 N 个方法。
class MyClass
def self.method_one(params)
#specific code
end
def self.method_two(params)
#specific code
end
end
我需要为在 class 中创建的每个方法添加相同的代码。我需要将代码放在“begin 和 rescue”
之间
我尝试了以下方法,但没有成功:
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
是一个class方法,换句话说,是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
我有一个 class 有 N 个方法。
class MyClass
def self.method_one(params)
#specific code
end
def self.method_two(params)
#specific code
end
end
我需要为在 class 中创建的每个方法添加相同的代码。我需要将代码放在“begin 和 rescue”
之间我尝试了以下方法,但没有成功:
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
是一个class方法,换句话说,是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