Class: Activr::Dispatcher

Inherits:
Object
  • Object
show all
Defined in:
lib/activr/dispatcher.rb

Overview

The dispatcher is the component that is in charge of routing activities to timelines.

The dispatcher singleton is accessible with dispatcher

Instance Method Summary collapse

Instance Method Details

#recipients_for_timeline(timeline_class, activity) ⇒ Hash{Object=>Timeline::Route}

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

Find recipients for given activity in given timeline

Parameters:

  • timeline_class (Class)

    Timeline class

  • activity (Activity)

    Activity instance

Returns:



47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
# File 'lib/activr/dispatcher.rb', line 47

def recipients_for_timeline(timeline_class, activity)
  result = { }

  routes = timeline_class.routes_for_activity(activity.class)
  routes.each do |route|
    route.resolve(activity).each do |recipient|
      recipient_id = timeline_class.recipient_id(recipient)

      # keep only one route per recipient
      if result[recipient_id].nil?
        result[recipient_id] = { :rcpt => recipient, :route => route }
      end
    end
  end

  result.inject({ }) do |memo, (recipient_id, infos)|
    memo[infos[:rcpt]] = infos[:route]
    memo
  end
end

#route(activity) ⇒ Integer

Route an activity

Parameters:

  • activity (Activity)

    Activity to route

Returns:

  • (Integer)

    The number of resolved recipients that will handle activity



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
# File 'lib/activr/dispatcher.rb', line 14

def route(activity)
  raise "Activity must be stored before routing: #{activity.inspect}" if !activity.stored?

  result = 0

  activity.run_callbacks(:route) do
    # iterate on all timelines
    Activr.registry.timelines.values.each do |timeline_class|
      # check if timeline refuses that activity
      next unless timeline_class.should_route_activity?(activity)

      # store activity in timelines
      self.recipients_for_timeline(timeline_class, activity).each do |recipient, route|
        result += 1

        timeline = timeline_class.new(recipient)
        if timeline.should_handle_activity?(activity, route)
          Activr::Async.hook(:timeline_handle, timeline, activity, route)
        end
      end
    end
  end

  result
end