class Decidim::ContentParsers::HashtagParser

A parser that searches hashtags in content.

A word starting with `#` will be considered as a hashtag if it only contains letters, numbers or underscores. If the `#` is followed with an underscore, then it is not considered.

@see BaseParser Examples of how to use a content parser

Constants

HASHTAG_REGEX

Matches a hashtag if it starts with a letter or number and only contains letters, numbers or underscores.

Metadata

Class used as a container for metadata

@!attribute hashtags

@return [Array] an array of Decidim::Hashtag mentioned in content

Public Instance Methods

metadata() click to toggle source
# File lib/decidim/content_parsers/hashtag_parser.rb, line 32
def metadata
  Metadata.new(content_hashtags.map { |content_hashtag| hashtag(content_hashtag) }.uniq)
end
rewrite() click to toggle source

Replaces hashtags name with new or existing hashtags models global ids.

@return [String] the content with the hashtags replaced by global ids

# File lib/decidim/content_parsers/hashtag_parser.rb, line 26
def rewrite
  content.gsub(HASHTAG_REGEX) do |match|
    "#{hashtag(match[1..-1]).to_global_id}/#{(extra_hashtags? ? "_" : "")}#{match[1..-1]}"
  end
end

Private Instance Methods

content_hashtags() click to toggle source
# File lib/decidim/content_parsers/hashtag_parser.rb, line 51
def content_hashtags
  @content_hashtags ||= content.scan(HASHTAG_REGEX).flatten.uniq
end
current_organization() click to toggle source
# File lib/decidim/content_parsers/hashtag_parser.rb, line 55
def current_organization
  @current_organization ||= context[:current_organization]
end
existing_hashtags() click to toggle source
# File lib/decidim/content_parsers/hashtag_parser.rb, line 47
def existing_hashtags
  @existing_hashtags ||= Decidim::Hashtag.where(organization: current_organization, name: content_hashtags.map(&:downcase))
end
extra_hashtags?() click to toggle source
# File lib/decidim/content_parsers/hashtag_parser.rb, line 59
def extra_hashtags?
  return @extra_hashtags if defined?(@extra_hashtags)

  @extra_hashtags = context[:extra_hashtags]
end
hashtag(name) click to toggle source
# File lib/decidim/content_parsers/hashtag_parser.rb, line 38
def hashtag(name)
  hashtags[name.downcase] ||= Decidim::Hashtag.create(organization: current_organization, name: name.downcase)
end
hashtags() click to toggle source
# File lib/decidim/content_parsers/hashtag_parser.rb, line 42
def hashtags
  @hashtags ||=
    existing_hashtags.index_by(&:name)
end