Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

After_save with parameter

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!

like image 770
John Smith Avatar asked Jan 10 '23 05:01

John Smith


1 Answers

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

like image 140
Fer Avatar answered Jan 18 '23 00:01

Fer