Skip to content

Instantly share code, notes, and snippets.

@Inviz
Created March 6, 2009 07:12
Show Gist options
  • Select an option

  • Save Inviz/74805 to your computer and use it in GitHub Desktop.

Select an option

Save Inviz/74805 to your computer and use it in GitHub Desktop.
class Activity
module FactoryMethods
%w[
project_created
lab_created
person_joined_project
person_left_project
person_created_message
person_published_message
person_created_discussion
person_created_discussion_reply_in_discussion
person_started_following_another_person
person_stopped_following_another_person
].each do |name|
#extract object, action and subjects
object, subjects = name.split("_", 2)
action, *subjects = subjects.split(/_?(?:in_)?((?:another|starting|started)?_?[^_]+(?:_(?:reply|category|comment))?)/).reject{|i| i.blank?}
subject = subjects.first
#there are only 2 arguments - object and subject.
args = [object, subject].compact * ", "
#remove me if DM bug is ever fixed. this soloely is a bug workaround
subjects.each_with_index do |thing, i|
subjects[i] = \
if i == 0
thing
else
"#{thing}_id"
end
end
#other subjects are gotten from first subject, e.g. project = subject.project
getters = (subjects[1, 10] || []).map {|i| "#{i} = #{subject}.#{i}"} * "\n"
project = "project ||= " + \
if subject
subjects << "project"
"#{subject}.respond_to?(:project) ? #{subject}.project : nil"
else
"nil"
end
everything = [object, *subjects]
hash = everything.map{|i| ":#{i} => #{i}"} * ", "
recipients = {
:public => everything.grep(/project$|lab$/),
:members => everything.grep(/project$|lab$/),
:followers => everything.grep(/person$/),
:people => everything.grep(/person$/)
}
{
"" => recipients.map{|group, subjects| ":#{group} => [#{subjects * ', '}]"} * ", ",
"!" => recipients.only(:public, :people).map{|group, subjects| ":#{group} => [#{subjects * ', '}]"} * ", "
}.each do |excl, recipients|
class_eval %{
def #{name}#{excl}(#{args})
#{getters}
#{project}
activity = create(:type => "#{name}", #{hash})
self.deliver activity, #{recipients}
activity
end
}
end
end
def deliver(activity, options = {})
recipients = []
recipients += [*options[:members]].compact.map{|i| i.members} if options[:members]
recipients += [*options[:followers]].compact.map{|i| i.followed_by_people} if options[:followers]
recipients -= [*options[:people]].compact if options[:person]
recipients.flatten.uniq.compact.each do |recipient|
recipient.private_activity!(activity)
end
if options[:public]
[options[:public], options[:people]].flatten.uniq.compact.each do |recipient|
recipient.public_activity!(activity)
end
end
activity
end
end # ActivityHooks
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment