带参数的After_save

时间:2014-12-19 13:44:39

标签: ruby-on-rails ruby ruby-on-rails-3 model

这是我的型号代码:

after_create :notify_cards_create
after_destroy :notify_cards_destroy
after_update :notify_cards_update

def notify_cards_update
   WebsocketRails[:home].trigger 'cards', {type: 'update', card: self.as_json({small: true})}
end

def notify_cards_create
    WebsocketRails[:home].trigger 'cards', {type: 'create', card: self.as_json({small: true})}
end

def notify_cards_destroy
    WebsocketRails[:home].trigger 'cards', {type: 'destroy', card: self.as_json({small: true})}
end

正如您所看到的,它包含许多重复内容!如何将此代码缩短为:

after_create :notify_cards_create,   'create'
after_destroy :notify_cards_destroy, 'destroy'
after_update :notify_cards_update,   'update'

谢谢!

1 个答案:

答案 0 :(得分:7)

我会像这样实现它:

after_create ->(obj) { notify_cards('create') }
after_destroy ->(obj) { notify_cards('update') }
after_update ->(obj) { notify_cards('destroy') }

protected 

def notify_cards(event_type)
  WebsocketRails[:home].trigger 'cards', {type: event_type, card: self.as_json({small: true})}
end

lambda的obj参数不是必需的,但是如果要访问正在创建/更新/删除的对象,则可以使用它。