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',
  'ola': 'alpha-ordered-list',
  'ol': 'ordered-list',
  'ul': 'unordered-list',
  'table': 'table',
  'tbody': 'tbody',
  'tr': 'tr',
  'td': 'td',
  'text': 'text'
}.freeze
BLOCK_ELEMENTS =

Default block types list

%w[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 Slare 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



42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
# File 'lib/slate_serializer/html.rb', line 42

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

  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