Module: Activist::Store::InstanceMethods

Defined in:
lib/activist/store.rb

Instance Method Summary collapse

Instance Method Details

#store_activities(stream, options = {}) ⇒ Object

Options: :actor (optional) :action (optional) :on (optional) :data (optional) :if (optional) :unless (optional)



13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
# File 'lib/activist/store.rb', line 13

def store_activities(stream, options = {})
  options.symbolize_keys!
  
  callback = options.delete(:on)
  
  if_condition = case options[:if]
    when Symbol
      send(options[:if])
    when Proc
      options[:if].call(self)
    else
      true
  end
  return unless if_condition
  
  unless_condition = case options[:unless]
    when Symbol
      send(options[:unless])
    when Proc
      options[:unless].call(self)
    else
      false
  end
  return if unless_condition
  
  actor = case options[:actor]
    when nil
      send(:user)
    when Symbol
      send(options[:actor])
    when Proc
      options[:actor].call(self)
    else
      options[:actor]
  end
  
  action = if options[:action].nil?
    case callback
      when :before_create, :after_create
        options[:action] = :created
      when :before_save, :after_save
        options[:action] = :saved
      when :before_update, :after_update
        options[:action] = :updated
      when :before_destroy, :after_destroy
        options[:action] = :destroyed
      else
        nil
    end
  else
    options[:action]
  end
  
  data = case options[:data]
    when Hash, Array
      options[:data]
    when Proc
      options[:data].call(self)
    else
      nil
  end
  
  subscribers = actor.send("#{stream}_stream").subscribers
  if subscribers.any?
    status = ::ActivistStatus.create! do |s|
      s.actor_class = actor.class.to_s
      s.actor_id = actor.id
      s.action = action
      s.target_class = self.class.to_s
      s.target_id = self.id
      s.data = data
      s.created_at = Time.now.utc
    end
    subscribers.each do |subscriber|
      Redis.execute.lpush("#{subscriber.class}.#{subscriber.id}:#{stream}", status.id)
    end
  end
end