docbrown/app/helpers/admin_helper.rb
Jeremy Friesen 71e9f2bfb4
Refactoring AdminMenu and Menu towards classes (#16847)
As I was looking to implement the new Spaces feature (see
forem/forem#16842), I began looking at how to adjust the admin menu.  I
found the Menu and AdminMenu.  I wanted to add the "spaces" item under
the `:content_manager` scope.  Looking at the implementation, I saw I
would need some additional branching logic.

To get an understanding of the implementation, I chose factor towards
classes.

This refactor does a few things:

1) Clarifies a method name (e.g. "children?" becomes
   "has_multiple_children?")
2) Adds some tests of the menu implementation.
3) Removes deeply nested hashs in favor of first class objects.
4) Removes a complex method for determining menu visibility, instead
   favoring a method that either takes a boolean OR a lambda.

There are further refactors to consider, especially in regards to the
helper methods and some of the coercion of strings into different
formats.  But this refactor gets me the part I most am interested in:

Making it easier to specify a menu item as visible or not.
2022-03-21 13:31:20 -04:00

33 lines
978 B
Ruby

module AdminHelper
def deduced_controller(request)
request.path.split("/").fourth
end
def deduced_scope(request)
request.path.split("/").third
end
def display_name(group_name)
group_name.to_s.tr("_", " ").titleize
end
def dom_safe_name(group_name)
group_name.gsub(/\s+|\./, "_").gsub(/\A(\d)/, '_\1')
end
def current?(request, group, group_name)
deduced_scope(request).to_s == (group.children.first&.parent || group_name).to_s
end
def nav_path(group, group_name)
if group.has_multiple_children?
# NOTE: [@jeremyf] I'm unclear what to do if we have no match; this logic
# carries forward the prior implementation.
visible_child_controller = group.children.detect(&:visible?)&.controller
"#{admin_path}/#{group_name}/#{visible_child_controller}"
else
# NOTE: We assume that if there's only one child that it is visible
"#{admin_path}/#{group.children.first&.controller}"
end
end
end