This is my model code:
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
As you can see it contains many duplications! How can i shorten this code to something like:
after_create :notify_cards_create, 'create'
after_destroy :notify_cards_destroy, 'destroy'
after_update :notify_cards_update, 'update'
Thank you!
I would implement it like this:
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
The obj
parameter to the lambda is not mandatory, but you have it available if you want to access the object being created/updated/deleted
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With