Class: NotionToMd::Blocks::Normalizer

Inherits:
Object
  • Object
show all
Defined in:
lib/notion_to_md/blocks/normalizer.rb

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(blocks:) ⇒ Normalizer

Returns a new instance of Normalizer.



16
17
18
19
# File 'lib/notion_to_md/blocks/normalizer.rb', line 16

def initialize(blocks:)
  @blocks = blocks
  @normalized_blocks = blocks
end

Instance Attribute Details

#blocksObject (readonly)

Returns the value of attribute blocks.



14
15
16
# File 'lib/notion_to_md/blocks/normalizer.rb', line 14

def blocks
  @blocks
end

#normalized_blocksObject (readonly)

Returns the value of attribute normalized_blocks.



14
15
16
# File 'lib/notion_to_md/blocks/normalizer.rb', line 14

def normalized_blocks
  @normalized_blocks
end

Class Method Details

.normalize(blocks:) ⇒ Object

Parameters

blocks

An array of NotionToMd::Blocks::Block.



10
11
12
# File 'lib/notion_to_md/blocks/normalizer.rb', line 10

def self.normalize(blocks:)
  new(blocks: blocks).normalize
end

Instance Method Details

#normalizeObject



21
22
23
24
25
# File 'lib/notion_to_md/blocks/normalizer.rb', line 21

def normalize
  normalize_for :bulleted_list_item
  normalize_for :numbered_list_item
  normalize_for :to_do
end

#normalize_for(type) ⇒ Object



27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
# File 'lib/notion_to_md/blocks/normalizer.rb', line 27

def normalize_for(type)
  new_blocks = []

  normalized_blocks.each do |block|
    if block.type.to_sym == type
      blocks_to_normalize << block
    else
      # When we encounter a block that is not of the provided type,
      # we need to normalize the blocks we've collected so far.
      # Then we add the current block to the new blocks array.
      # This is because we want to keep the order of the blocks.
      new_blocks << new_block_and_reset(type, blocks_to_normalize) unless blocks_to_normalize.empty?
      new_blocks << block
    end
  end

  # If the last block is of the provided type, it won't be added to the new blocks array.
  # So, we need to normalize the blocks we've collected so far.
  new_blocks << new_block_and_reset(type, blocks_to_normalize) unless blocks_to_normalize.empty?

  normalized_blocks.replace(new_blocks)
end