Sha256: c06b8e80bbe940476890a018aa39545e6bcec3683328569b8c9d1f663c29733b

Contents?: true

Size: 1.78 KB

Versions: 2

Compression:

Stored size: 1.78 KB

Contents

# frozen_string_literal: true

module Decidim
  module ContentRenderers
    # 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
    #
    # @see BaseRenderer Examples of how to use a content renderer
    class HashtagRenderer < BaseRenderer
      # Matches a global id representing a Decidim::Hashtag
      GLOBAL_ID_REGEX = %r{gid:\/\/[\w-]*\/Decidim::Hashtag\/(\d+)}

      # 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.
      #
      # @return [String] the content ready to display (contains HTML)
      def render
        content.gsub(GLOBAL_ID_REGEX) do |hashtag_gid|
          begin
            hashtag = GlobalID::Locator.locate(hashtag_gid)
            Decidim::HashtagPresenter.new(hashtag).display_hashtag
          rescue ActiveRecord::RecordNotFound => _ex
            ""
          end
        end
      end

      def render_without_link
        if content.is_a?(Hash)
          content.each_with_object({}) do |(locale, string), parsed_content|
            parsed_content[locale] = replace_hashtag_gid_with_hashtag_name(string)
          end
        else
          replace_hashtag_gid_with_hashtag_name(content)
        end
      end

      def replace_hashtag_gid_with_hashtag_name(content)
        content.gsub(GLOBAL_ID_REGEX) do |hashtag_gid|
          begin
            hashtag = GlobalID::Locator.locate(hashtag_gid)
            Decidim::HashtagPresenter.new(hashtag).display_hashtag_name
          rescue ActiveRecord::RecordNotFound => _ex
            ""
          end
        end
      end
    end
  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
decidim-core-0.15.2 lib/decidim/content_renderers/hashtag_renderer.rb
decidim-core-0.15.1 lib/decidim/content_renderers/hashtag_renderer.rb