2010-02-10 74 views
1

我们在很多模型中使用AASM,但我们正在考虑简化模型。我们想要做的事情之一就是将所有通知内容从模型中移到观察者中。与事件挂钩的观察者

因此,考虑:

class ClarificationRequest < ActiveRecord::Base 
    include AASM 

    aasm_initial_state :open 

    # States 
    aasm_state :open 
    aasm_state :closed 

    # Events 
    aasm_event :close, :after => :notify_closed do transitions :to => :closed, :from => [:open,:replied], :guard => :can_close? end 
end 

我想这一点,但没有运气:

class ClarificationRequestObserver < ActiveRecord::Observer 
    observe :clarification_request 

    def after_close 
    puts '############### message from observer!!!!!' 
    end 
end 

我如何可以移动:notify_closed以观察员?

Thx!

。卡林

回答

0

说实话,我觉得你怎么这样很好。将AASM挂钩用于这样的东西是有道理的。这样你就知道它已经过渡了,然后你发送了通知。

你可以看看在before_update中使用活动记录dirty来检查state_was是否打开并且现在关闭。

+0

我们用这种方法遇到的一个主要问题是,我们实际上想要创建也需要具有current_user_id的事件(一种审计模型),并且据我所知,并不容易或不适合方式包括在模型...因此观察员? – khelal 2010-02-10 10:55:11

+0

虽然这可能并不理想,但您可以像这样获取用户标识:在用户模型中添加cattr_accessor:current_user。在应用程序控制器中添加一个调用def的before_filter set_current_user User.current_user = self.current_user – tsdbrown 2010-02-10 11:55:08

1

我已经回答GitHub上的评论之前,我将在这里重复,以防万一

class ClarificationRequest < ActiveRecord::Base 
    include AASM 

    aasm_initial_state :open 

    # States 
    aasm_state :open 
    aasm_state :closed 

    # Events 
    aasm_event :close, :after => :notify_closed do transitions :to => :closed, :from => [:open,:replied], :guard => :can_close? end 

    # Notify Observer 
    def notify_closed 
    notify :close # this will trigger after_close method call in ClarificationRequestObserver 
    # notify :closed # this will trigger after_closed method call in ClarificationRequestObserver 
    # notify :whatever # this will trigger after_whatever method call in ClarificationRequestObserver 
    end 
end 
+0

这是一个努力工作的家伙。 – Jaryl 2010-03-07 09:45:47

+0

感谢您的提示。我会为它+1,但评论是误导性的。 'notify:close'实际上会调用'ClarificationRequestObserver#close'(并且#after_close后面的** not **) – averell 2012-08-01 14:15:59

0

我会做这样的事情:

class ClarificationRequest < ActiveRecord::Base 
    include AASM 

    aasm_initial_state :open 

    # States 
    aasm_state :open 
    aasm_state :closed, :enter => :do_close 

    # Events 
    aasm_event :close do transitions :to => :closed, :from => [:open,:replied], :guard => :can_close? end 

    def recently_closed? 
    @recently_closed 
    end 
protected 
    def do_close 
    @recently_closed = true 
    end 

end 


class ClarificationRequestObserver < ActiveRecord::Observer 
    observe :clarification_request 

    def after_save(clarification_request) 
    puts '############### message from observer!!!!!' if clarification_request.recently_closed? 
    end 
end 

你还应该包括在config/environment.rb中的config.active_record.observers列表中的观察者

原因是观察者应该观察一个对象。通过主动向模型中的观察者通知(并与之交互),你假设有一个可用的,我不相信你能安全地做到的(看到观察者通常如何在现实世界中表现)。它应该由观察者决定是否对事件感兴趣。