module Stream module Fires def self.included(klass) klass.send(:extend, ClassMethods) end module ClassMethods def fires(activity_type, opts) raise ArgumentError, "Argument :on is mandatory" unless opts.has_key?(:on) # Array provided, set multiple callbacks if opts[:on].kind_of?(Array) opts[:on].each { |on| fires(activity_type, opts.merge({:on => on})) } return end opts[:subject] = :self unless opts.has_key?(:subject) method_name = :"fire_#{activity_type}_after_#{opts[:on]}" define_method(method_name) do create_options = [:actor, :subject, :secondary_subject, :is_hidden].inject({}) do |memo, sym| if opts[sym] if opts[sym].respond_to?(:call) memo[sym] = opts[sym].call(self) elsif opts[sym] == :self memo[sym] = self else memo[sym] = send(opts[sym]) end end memo end create_options[:activity_type] = activity_type.to_s activity = ActivityItem.create(create_options) if activity_type.to_s.eql?'new_message' activity.subject.recipient.activity_items << activity elsif activity_type.to_s.eql?'new_photo' last_activity = ActivityItem.find(:first, :conditions => ["subject_type = ? AND photos.gallery_id = ? AND DATE(activity_items.updated_at) = current_date", activity.subject.class,activity.subject.gallery_id],:include=>[:photos]) if last_activity && (activity.subject.gallery.eql?(last_activity.subject.gallery)) last_activity.photos << activity.subject last_activity.update_attribute(:updated_at,Time.now) activity.destroy else ([activity.actor] + activity.subject.gallery.allowed_contacts).each do |p| activity.is_hidden = activity.subject.approval_status==0 ? true : false activity.photos << activity.subject activity.save p.activity_items << activity end end else ([activity.actor] + activity.actor.contacts).each{|p| p.activity_items << activity } end end send(:"after_#{opts[:on]}", method_name, :if => opts[:if]) end end end end