在ruby方法中定义自定义回调

在ruby方法中定义自定义回调

问题描述:

我有很多服务类,其中call方法的参数有变化。在ruby方法中定义自定义回调

我想在每个call方法的末尾调用函数notify。我不想修改这些服务类,但我愿意修改基类。

我在玩ActiveSupport::Callbacks,但它没有服务于不修改服务类的目的。

require 'active_support' 
class Base 
    include ActiveSupport::Callbacks 
    define_callbacks :notifier 

    set_callback :notifier, :after do |object| 
    notify() 
    end 

    def notify 
    puts "notified successfully" 
    end 
end 

class NewPost < Base 
    def call 
    puts "Creating new post on WordPress" 
    # run_callbacks :notifier do 
    # puts "notifying....." 
    # end 
    end 
end 

class EditPost < Base 
    def call 
    puts "Editing the post on WordPress" 
    # run_callbacks :notifier do 
    # puts "notified successfully" 
    # end 
    end 
end 

person = NewPost.new 
person.call 

问题为了运行回调,我需要取消对注释的代码。但在这里你可以看到我需要修改现有的类来添加run_callbacks块。但那不是我想要的。我可以轻松地调用notify方法,而不会增加这种复杂性。

任何人都可以建议我怎么才能达到解决方案的红宝石方式?

我会做这样的事情:

require 'active_support' 
class Base 
    include ActiveSupport::Callbacks 
    define_callbacks :notifier 

    set_callback :notifier, :after do |object| 
    notify() 
    end 

    def notify 
    puts "notified successfully" 
    end 

    def call 
    run_callbacks :notifier do 
     do_call 
    end 
    end 

    def do_call 
    raise 'this should be implemented in children classes' 
    end 
end 

class NewPost < Base 
    def do_call 
    puts "Creating new post on WordPress" 
    end 
end 

person = NewPost.new 
person.call 

另一种解决方案,而不的ActiveSupport:

module Notifier 
    def call 
    super 
    puts "notified successfully" 
    end 
end 


class NewPost 
    prepend Notifier 

    def call 
    puts "Creating new post on WordPress" 
    end 
end 

NewPost.new.call 

您应该检查你的Ruby版本prepend是一个 “新” 的方法(2.0)

+0

外貌好,但它又不能达到目的。我不想改变所有的孩子班。此外,您建议的解决方案也需要更改所有对“调用”方法的引用。 –

+1

这是在Rails中使用ActiveSupport :: Callbacks的方式......您也可以预先安装一个通知器模块(参见编辑答案) – ThomasSevestre

+0

Awsome。我爱第二个解决方案。谢谢 –