Class: Jekyll::GeneratorSingleSource::NavConfig::Patch

Inherits:
Object
  • Object
show all
Defined in:
lib/jekyll/generator-single-source/nav_config/patch.rb

Constant Summary collapse

ACTIONS =
['append', 'delete', 'modify', 'insert'].freeze

Instance Method Summary collapse

Constructor Details

#initialize(patch, items) ⇒ Patch

Returns a new instance of Patch.

Raises:

  • (ArgumentError)


9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
# File 'lib/jekyll/generator-single-source/nav_config/patch.rb', line 9

def initialize(patch, items)
  @path = patch.fetch('path', [])
  @action = patch.fetch('action', 'append')
  @idx = patch.fetch('index', nil)
  @entries = patch.fetch('entries', nil)
  @items = items

  unless ACTIONS.include? @action
    raise ArgumentError.new("action can only be #{ACTIONS.join(', ')} got `#{@action}` for patch #{patch.inspect}")
  end

  if @action == 'insert' && @idx == nil
    raise ArgumentError.new("when using insert action you must set 'index' for patch #{patch.inspect}")
  end

  if @action == 'delete' && @entries == nil
    raise ArgumentError.new("when using delete action you must set 'entries' for patch #{patch.inspect}")
  end

  raise ArgumentError.new("path must be an array for patch #{patch.inspect}") unless @path.is_a?(Array)

  @patch = patch.except('action', 'path', 'index')
end

Instance Method Details

#applyObject



33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
# File 'lib/jekyll/generator-single-source/nav_config/patch.rb', line 33

def apply
  @path.each do |p|
    all = @items.fetch('items', []).select do |i|
      (i.fetch('title') {|_| i.fetch('text')}) == p
    end
    @items = all.fetch(0) { raise "Couldn't find docs section with title or text '#{p}' to apply delete patch #{self.inspect}" }
  end

  if @action == "delete"
    @entries.each do |entry|
      idx = @items['items'].index {|item| (item.fetch('title') {|_| item.fetch('text')}) == entry}
      raise "Couldn't find docs section with title or text '#{entry}' to apply delete patch #{self.inspect}" unless idx != nil
      @items['items'].delete_at(idx)
    end
  elsif @action == "modify"
    @items.merge!(@patch)
  elsif @action == "insert"
    @items['items'].insert(@idx, @patch)
  elsif @action == "append"
    @items['items'].push(@patch)
  end
end