summaryrefslogtreecommitdiff
path: root/app/helpers/breadcrumbs_helper.rb
blob: 3a622a656856385856515ea150ff1668ef64e533 (plain)
1
2
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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
# frozen_string_literal: true

module BreadcrumbsHelper
  def add_to_breadcrumbs(text, link)
    @breadcrumbs_extra_links ||= []
    @breadcrumbs_extra_links.push({
      text: text,
      link: link
    })
  end

  def breadcrumb_title_link
    return @breadcrumb_link if @breadcrumb_link

    request.path
  end

  def breadcrumb_title(title)
    return if defined?(@breadcrumb_title)

    @breadcrumb_title = title
  end

  def breadcrumb_list_item(link)
    content_tag "li" do
      link + sprite_icon("angle-right", size: 8, css_class: "breadcrumbs-list-angle")
    end
  end

  def add_to_breadcrumb_collapsed_links(link, location: :before)
    @breadcrumb_collapsed_links ||= {}
    @breadcrumb_collapsed_links[location] ||= []
    @breadcrumb_collapsed_links[location] << link
  end

  def push_to_schema_breadcrumb(text, link)
    list_item = schema_list_item(text, link, schema_breadcrumb_list.size + 1)

    schema_breadcrumb_list.push(list_item)
  end

  def schema_breadcrumb_json
    {
      '@context': 'https://schema.org',
      '@type': 'BreadcrumbList',
      'itemListElement': build_item_list_elements
    }.to_json
  end

  private

  def schema_breadcrumb_list
    @schema_breadcrumb_list ||= []
  end

  def build_item_list_elements
    return @schema_breadcrumb_list unless @breadcrumbs_extra_links&.any?

    last_element = schema_breadcrumb_list.pop

    @breadcrumbs_extra_links.each do |el|
      push_to_schema_breadcrumb(el[:text], el[:link])
    end

    last_element['position'] = schema_breadcrumb_list.last['position'] + 1
    schema_breadcrumb_list.push(last_element)
  end

  def schema_list_item(text, link, position)
    {
      '@type' => 'ListItem',
      'position' => position,
      'name' => text,
      'item' => ensure_absolute_link(link)
    }
  end

  def ensure_absolute_link(link)
    url = URI.parse(link)
    url.absolute? ? link : URI.join(request.base_url, link).to_s
  rescue URI::InvalidURIError
    "#{request.base_url}#{request.path}"
  end
end