Created
June 10, 2015 18:22
-
-
Save heavysixer/181b19b4b7f6c2deee07 to your computer and use it in GitHub Desktop.
A Public::Activity concern which allows you to create custom activities when arbitrary triggers occur.
This file contains 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
# PublicActivity Concern to allow custom activities to be created when certain triggers occur. | |
# | |
# Usage Example: | |
# | |
# class Challenge < ActiveRecord::Base | |
# include Eventable | |
# eventable :after_save => [{ | |
# key: 'challenge.after_publish', | |
# when: "self.public_changed? && self.public?", | |
# recipients: 'self.potential_members' | |
# }, | |
# { | |
# key: 'challenge.winners_chosen', | |
# when: "self.status_id_changed? && self.status == 'Winners Chosen'", | |
# recipients: 'self.entrants' | |
# }, | |
# { | |
# key: 'challenge.closed', | |
# when: "self.status_id_changed? && self.status == 'Closed'", | |
# recipients: 'self.potential_members' | |
# }] | |
module Eventable | |
extend ActiveSupport::Concern | |
module ClassMethods | |
def eventable(*arr) | |
arr.each do |options| | |
options.keys.each do |kallback| | |
define_method "eventable_#{kallback}" do | |
self.instance_variable_set("@_#{kallback}_hooks", options[kallback]) | |
end | |
self.send(kallback, proc { self.send(:process_events_for, self.send("eventable_#{kallback}"))}) | |
end | |
end | |
end | |
end | |
included do | |
include PublicActivity::Common | |
end | |
def process_events_for(arr) | |
arr.each do |a| | |
if a[:when].nil? || eval(a[:when]) | |
(eval(a[:recipients]) || []).each do |recipient| | |
self.create_activity key: a[:key], owner: self, recipient: recipient, parameters: a[:parameters] || {} | |
end | |
end | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment