Class: Decidim::ContentRenderers::HashtagRenderer

Inherits:
BaseRenderer
  • Object
show all
Defined in:
decidim-core/lib/decidim/content_renderers/hashtag_renderer.rb

Overview

A renderer that searches Global IDs representing hashtags in content and replaces it with a link to their detail page with the name.

e.g. gid://<APP_NAME>/Decidim::Hashtag/1

Constant Summary collapse

GLOBAL_ID_REGEX =

Matches a global id representing a Decidim::Hashtag

%r{gid://[\w-]*/Decidim::Hashtag/(\d+)/?(_?)([[:alnum:]](?:[[:alnum:]]|_)*)?\b}

Instance Attribute Summary

Attributes inherited from BaseRenderer

#content

Instance Method Summary collapse

Methods inherited from BaseRenderer

#initialize

Methods included from Decidim::ContentProcessor::Common

#html_content?, #html_fragment

Constructor Details

This class inherits a constructor from Decidim::ContentRenderers::BaseRenderer

Instance Method Details

#extra_hashtagsObject

Returns all the extra hashtags found in the content



46
47
48
# File 'decidim-core/lib/decidim/content_renderers/hashtag_renderer.rb', line 46

def extra_hashtags
  @extra_hashtags ||= existing_hashtags.select { |hashtag| content_extra_hashtags_ids.member?(hashtag.id) }
end

#render(links: true, extras: true, editor: false) ⇒ String

Replaces found Global IDs matching an existing hashtag with a link to their detail page. The Global IDs representing an invalid Decidim::Hashtag are replaced with an empty string.

links - should render hashtags as links? extras - should include extra hashtags?

Returns:

  • (String)

    the content ready to display (contains HTML)



23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
# File 'decidim-core/lib/decidim/content_renderers/hashtag_renderer.rb', line 23

def render(links: true, extras: true, editor: false)
  return content unless content.respond_to?(:gsub)

  content.gsub(GLOBAL_ID_REGEX) do |hashtag_gid|
    id, extra, cased_name = hashtag_gid.scan(GLOBAL_ID_REGEX).flatten
    hashtag = hashtags[id.to_i]

    next "" if hashtag.nil? || (!extras && extra.present?)

    presenter = Decidim::HashtagPresenter.new(hashtag, cased_name:)

    if editor
      label = presenter.display_hashtag_name
      %(<span data-type="hashtag" data-label="#{label}">#{label}</span>)
    elsif links
      presenter.display_hashtag
    else
      presenter.display_hashtag_name
    end
  end
end