Class: Super::Navigation::Automatic

Inherits:
Object
  • Object
show all
Defined in:
lib/super/navigation/automatic.rb

Instance Method Summary collapse

Constructor Details

#initialize(route_namespace:) ⇒ Automatic

Returns a new instance of Automatic.



4
5
6
7
8
9
10
11
12
# File 'lib/super/navigation/automatic.rb', line 4

def initialize(route_namespace:)
  route_namespace = route_namespace.to_s

  if route_namespace.include?("/")
    raise "Can't be nested namespace"
  end

  @route_namespace = route_namespace
end

Instance Method Details

#eachObject



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
# File 'lib/super/navigation/automatic.rb', line 14

def each
  if !block_given?
    return enum_for(:each)
  end

  navigable_namespace_routes = Rails.application.routes.routes.select do |route|
    path_spec = route.path.spec

    next if route.verb != "GET"
    next if !path_spec.respond_to?(:right)
    next if path_spec.right.left.to_s != @route_namespace
    next if route.required_parts.any?
    next if route.defaults.empty?

    true
  end

  navigable_defaults = navigable_namespace_routes.map do |route|
    controller_name = route.defaults[:controller] + "_controller"
    _controller =
      begin
        controller_name.camelize.constantize
      rescue NameError
        warn("[super] Couldn't find controller: #{controller_name}")
        next
      end

    route.defaults
  end

  grouped_navigable_defaults =
    navigable_defaults.compact.uniq.group_by { |d| d[:controller] }

  grouped_navigable_defaults.each do |controller, defaults|
    actions = defaults.map { |d| [d[:action], d[:action]] }.to_h
    action = actions["index"] || actions["show"]

    next if action.nil?

    path =
      begin
        Rails.application.routes.url_for(
          controller: controller,
          action: action,
          only_path: true
        )
      rescue ActionController::UrlGenerationError
        next
      end

    yield(controller.split("/").last.humanize, path)
  end
end