Joh*_*ith 4 ruby model ruby-on-rails ruby-on-rails-3
这是我的型号代码:
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
Run Code Online (Sandbox Code Playgroud)
如你所见,它包含许多重复!如何将此代码缩短为:
after_create :notify_cards_create, 'create'
after_destroy :notify_cards_destroy, 'destroy'
after_update :notify_cards_update, 'update'
Run Code Online (Sandbox Code Playgroud)
谢谢!
我会像这样实现它:
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
Run Code Online (Sandbox Code Playgroud)
objlambda 的参数不是必需的,但如果要访问正在创建/更新/删除的对象,则可以使用它
| 归档时间: |
|
| 查看次数: |
1491 次 |
| 最近记录: |