KyivKrishnaAcademy/ved_akadem_students

View on GitHub
app/helpers/concerns/auto_generated_menu.rb

Summary

Maintainability
A
1 hr
Test Coverage
A
100%
module AutoGeneratedMenu
  include AbilityShortcuts

  SIDEBAR_MENU = [
    %i[program programs fa-sitemap],
    %i[course courses fa-book],
    %i[class_schedule class_schedules fa-calendar],
    %i[questionnaire questionnaires fa-question]
  ].freeze

  def active_class(*pathes)
    pathes.any? { |path| current_path?(path, enforce_params: true) } ? 'is-active' : ''
  end

  def generated_sidebar_menu
    safe_join(SIDEBAR_MENU.map { |name, plural_name, icon| generate_menu_group(name, plural_name, icon) })
  end

  def generate_menu_group(name, plural_name, icon, options = {}, &block)
    return unless send("show_#{plural_name}_menu?")

    content_tag :li do
      concat(check_box_tag(name, :checked, cookies["#{name}-submenu-is-opened"].present?, class: 'group-status'))
      concat(generate_label(name, plural_name, icon))
      concat(content_tag(:ul, generate_items(name, plural_name, block, options)))
    end
  end

  private

  def generate_label(name, plural_name, icon)
    label_tag name do
      concat(content_tag(:i, nil, class: "sidebar-icon fa fa-2x #{icon}", aria: { hidden: true }))
      concat(t("defaults.links.#{plural_name}"))
      concat(content_tag(:span, nil, class: :caret))
    end
  end

  def generate_items(name, plural_name, block, options)
    new_li = if !options[:skip_new] && current_person.can_act?("#{name}:new")
      new_path = send("new_#{name}_path")

      content_tag :li do
        link_to t("defaults.links.#{plural_name}_add"), new_path, class: active_class(new_path)
      end
    end

    list_li = if !options[:skip_list] && current_person.can_act?("#{name}:index")
      list_path = send("#{plural_name}_path")

      content_tag :li do
        link_to t("defaults.links.#{plural_name}_list"), list_path, class: active_class(list_path)
      end
    end

    safe_join([new_li, list_li, block&.call])
  end
end