Class: SlateSerializer::Html

Inherits:
Object
  • Object
show all
Defined in:
lib/slate_serializer/html.rb

Overview

Html de- and serializer

Constant Summary collapse

ELEMENTS =

Default lookup list to convert html tags to object types

{
  'a': 'link',
  'img': 'image',
  'li': 'list-item',
  'p': 'paragraph',
  'div': 'paragraph',
  'ol1': 'ordered-list',
  'ola': 'alpha-ordered-list',
  'ol': 'ordered-list',
  'ul': 'unordered-list',
  'table': 'table',
  'tbody': 'tbody',
  'tr': 'tr',
  'td': 'td',
  'text': 'text',
  'hr': 'hr',
  'figure': 'figure',
  'figcaption': 'figcaption'
}.freeze
BLOCK_ELEMENTS =

Default block types list

%w[figure figcaption hr img li p ol ul table tbody tr td].freeze
INLINE_ELEMENTS =

Default inline types list

%w[a].freeze
MARK_ELEMENTS =

Default mark types list

{
  'em': 'italic',
  'strong': 'bold',
  'u': 'underline'
}.freeze

Class Method Summary collapse

Class Method Details

.deserializer(html, options = {}) ⇒ Object

Convert html to a Slate document

Parameters:

  • html

    format [String] the HTML

  • options (Hash) (defaults to: {})

Options Hash (options):

  • :elements (Array)

    Lookup list to convert html tags to object types

  • :block_elemnts (Array)

    List of block types

  • :inline_elemnts (Array)

    List of inline types

  • :mark_elemnts (Array)

    List of mark types



46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
# File 'lib/slate_serializer/html.rb', line 46

def deserializer(html, options = {})
  return empty_state if html.nil? || html == ''

  self.elements = options[:elements] || ELEMENTS
  self.block_elements = options[:block_elements] || BLOCK_ELEMENTS
  self.inline_elements = options[:inline_elements] || INLINE_ELEMENTS
  self.mark_elements = options[:mark_elements] || MARK_ELEMENTS

  html = html.gsub('<br>', "\n")
  nodes = Nokogiri::HTML.fragment(html).elements.map do |element|
    element_to_node(element)
  end

  {
    document: {
      object: 'document',
      nodes: nodes
    }
  }
end

.serializer(value) ⇒ String

Convert html to a Slate document

Parameters:

  • value

    format [Hash] the Slate document

Returns:

  • (String)

    plain text version of the Slate documnent



71
72
73
74
75
# File 'lib/slate_serializer/html.rb', line 71

def serializer(value)
  return '' unless value.key?(:document)

  serialize_node(value[:document])
end