Last active
December 14, 2015 15:19
-
-
Save moretea/5106855 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| class Person | |
| include Webhook | |
| end | |
| module Webhook | |
| included do | |
| before_save :store_changes | |
| after_save :execute_webhook_after_save | |
| after_destroy :execute_webhook_after_destroy | |
| end | |
| def store_changes | |
| @was_new = self.new_record? | |
| @changes = self.changes.dup | |
| end | |
| def execute_webhook_after_save | |
| WebhookBackend.fire(self, (@was_new ? "created" : "updated"), @changes) | |
| end | |
| def execute_webhook_after_destroy | |
| WebhookBackend.fire(self, "destroyed", {}) | |
| end | |
| end | |
| module WebHookBackend | |
| def fire(model, event, changes) | |
| json = { | |
| model: model.class.name, | |
| model_id: model.id, | |
| event: event, | |
| changes: changes | |
| } | |
| # In some (ordered) background queue | |
| HTTP::Post.new(find_current_account.webhook_url, body: JSON.dump(json)) | |
| end | |
| end |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| /* Payload for new model */ | |
| { | |
| model: "Company", | |
| event: "created", | |
| model_id: 42, | |
| changes: { | |
| name: "AwesomeCompany" | |
| } | |
| } | |
| /* Payload for updated model */ | |
| { | |
| model: "Person", | |
| event: "update", | |
| model_id: 42, | |
| changes: { | |
| "first_name"=>["Maartn", "Maarten"]} | |
| } | |
| } | |
| /* Payload for destroyed model */ | |
| { | |
| model: "Person", | |
| event: "destroyed", | |
| model_id: 42 | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment