class Decidim::ContentParsers::PlanParser

A parser that searches mentions of Plans in content.

This parser accepts one way for linking Plans:

Also fills a `Metadata#linked_plans` attribute.

@see BaseParser Examples of how to use a content parser

Constants

ID_REGEX

Matches a mentioned Proposal ID (~(d)+ expression)

Metadata

Class used as a container for metadata

@!attribute linked_plans

@return [Array] an array of Decidim::Plans::Plan mentioned in content
URL_REGEX
URL_REGEX_CONTENT
URL_REGEX_END_CHAR
URL_REGEX_SCHEME

Matches a URL

Attributes

metadata[R]

(see BaseParser#metadata)

Public Class Methods

new(content, context) click to toggle source
Calls superclass method
# File lib/decidim/content_parsers/plan_parser.rb, line 28
def initialize(content, context)
  super
  @metadata = Metadata.new([])
end

Public Instance Methods

rewrite() click to toggle source

Replaces found mentions matching an existing Plan with a global id for that Plan. Other mentions found that doesn't match an existing Plan are returned as they are.

@return [String] the content with the valid mentions replaced by a

global id.
# File lib/decidim/content_parsers/plan_parser.rb, line 39
def rewrite
  parse_for_urls(content)
end

Private Instance Methods

find_plan_by_id(id) click to toggle source
# File lib/decidim/content_parsers/plan_parser.rb, line 71
def find_plan_by_id(id)
  if id.present?
    spaces = Decidim.participatory_space_manifests.flat_map do |manifest|
      manifest.participatory_spaces.call(context[:current_organization]).public_spaces
    end
    components = Component.where(participatory_space: spaces).published
    Decidim::Plans::Plan.where(component: components).find_by(id: id)
  end
end
parse_for_urls(content) click to toggle source
# File lib/decidim/content_parsers/plan_parser.rb, line 48
def parse_for_urls(content)
  content.gsub(URL_REGEX) do |match|
    plan = plan_from_url_match(match)
    if plan
      @metadata.linked_plans << plan.id
      plan.to_global_id
    else
      match
    end
  end
end
plan_from_url_match(match) click to toggle source
# File lib/decidim/content_parsers/plan_parser.rb, line 60
def plan_from_url_match(match)
  uri = URI.parse(match)
  return if uri.path.blank?

  plan_id = uri.path.split("/").last
  find_plan_by_id(plan_id)
rescue URI::InvalidURIError
  Rails.logger.error("#{e.message}=>#{e.backtrace}")
  nil
end