John Smith John Smith - 6 months ago 21
Ruby Question

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!

Fer Fer
Answer

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