Class: Decidim::ContentParsers::BaseParser Abstract

Inherits:
Object
  • Object
show all
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

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



27
28
29
30
# File 'lib/decidim/content_parsers/base_parser.rb', line 27

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



18
19
20
# File 'lib/decidim/content_parsers/base_parser.rb', line 18

def content
  @content
end

#contextHash (readonly)

Returns with context information.

Returns:

  • (Hash)

    with context information



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

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



58
59
60
# File 'lib/decidim/content_parsers/base_parser.rb', line 58

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



41
42
43
# File 'lib/decidim/content_parsers/base_parser.rb', line 41

def rewrite
  content
end