Class: Decidim::ContentParsers::BaseParser Abstract

Inherits:
Object
  • Object
show all
Includes:
Decidim::ContentProcessor::Common
Defined in:
lib/decidim/content_parsers/base_parser.rb

Overview

This class is abstract.

Subclass and override #rewrite and #metadata to implement a content parser

Abstract base class for content parsers, so they have the same contract

Examples:

How to use a content parser class

parser = Decidim::ContentParsers::CustomParser.new(content, context)
parser.rewrite # returns the content rewritten
parser. # returns a Metadata object

Constant Summary collapse

Metadata =

Class used as a container for metadata

Class.new

Instance Attribute Summary collapse

Instance Method Summary collapse

Methods included from Decidim::ContentProcessor::Common

#html_content?, #html_fragment

Constructor Details

#initialize(content, context) ⇒ BaseParser

Gets initialized with the ‘content` to parse

Parameters:

  • content (String)

    already rewritten content or regular content

  • context (Hash)

    arbitrary information to have a context



29
30
31
32
# File 'lib/decidim/content_parsers/base_parser.rb', line 29

def initialize(content, context)
  @content = content || ""
  @context = context
end

Instance Attribute Details

#contentString (readonly)

Returns the content to be rewritten.

Returns:

  • (String)

    the content to be rewritten



20
21
22
# File 'lib/decidim/content_parsers/base_parser.rb', line 20

def content
  @content
end

#contextHash (readonly)

Returns with context information.

Returns:

  • (Hash)

    with context information



23
24
25
# File 'lib/decidim/content_parsers/base_parser.rb', line 23

def context
  @context
end

Instance Method Details

#metadataMetadata

This method is abstract.

Subclass is expected to implement it

Collects and returns metadata. This metadata is accessible at parsing time so it can be acted upon (sending emails to the users) or maybe even stored at the DB for later consultation.

Examples:

Implementation for return a counter of prohibited words found

Metadata = Struct.new(:count)

def 
  Metadata.new(content.scan('foo').size)
end

Returns:

  • (Metadata)

    a Metadata object that holds extra information



60
61
62
# File 'lib/decidim/content_parsers/base_parser.rb', line 60

def 
  Metadata.new
end

#rewriteString

This method is abstract.

Subclass is expected to implement it

Parse the ‘content` and return it modified

Examples:

Implementation for search and mark prohibited words

def rewrite
  content.gsub('foo', '~~foo~~')
end

Returns:

  • (String)

    the content rewritten



43
44
45
# File 'lib/decidim/content_parsers/base_parser.rb', line 43

def rewrite
  content
end