Class: Routetracker::DashboardController

Inherits:
ApplicationController show all
Defined in:
app/controllers/routetracker/dashboard_controller.rb

Instance Method Summary collapse

Instance Method Details

#indexObject



3
4
5
6
7
8
9
10
11
12
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
# File 'app/controllers/routetracker/dashboard_controller.rb', line 3

def index
  @routes = []
  
  # Pre-fetch all hits to minimize queries
  # Grouping by controller#action allows us to aggregate multiple hits (e.g. different verbs for same action if applicable)
  all_hits = Routetracker::RouteHit.all
  hits_map = all_hits.group_by { |h| "#{h.controller}##{h.action}" }

  Rails.application.routes.routes.each do |route|
    # wrapper = ActionDispatch::Routing::RouteWrapper.new(route)
    # next if wrapper.internal? # internal? might not exist on raw route

    # requirements gives us the controller/action
    reqs = route.requirements
    controller = reqs[:controller]
    action = reqs[:action]
    
    next unless controller && action

    # Normalize data
    verb = route.verb.to_s
    path = route.path.spec.to_s
    # Remove (.:format) for cleaner display
    path = path.sub('(.:format)', '')

    key = "#{controller}##{action}"
    related_hits = hits_map[key] || []

    @routes << {
      verb: verb,
      path: path,
      controller: controller,
      action: action,
      hit_count: related_hits.sum(&:hit_count),
      last_hit_at: related_hits.map(&:last_hit_at).compact.max
    }
  end

  # Sort: Never hit first, then alphabetical
  @routes.sort_by! { |r| [r[:hit_count] == 0 ? 0 : 1, r[:controller], r[:action]] }
end