Class: Jekyll::FragmentGenerator

Inherits:
Generator
  • Object
show all
Defined in:
lib/jekyll-dry.rb

Constant Summary collapse

TagStart =
/#{Liquid::TagStart}#{Liquid::WhitespaceControl}?\s*/o
TagEnd =
/\s*#{Liquid::WhitespaceControl}?#{Liquid::TagEnd}/o
FragmentSubPattern =
/#{TagStart}(?i:(end)?frag)\s*(.*?)#{TagEnd}\s*/om
FullFragmentPattern =
%r/
  #{TagStart}(?i:frag)\s*(?<id>.*?)#{TagEnd}
  (?<body>.*)
  #{TagStart}(?i:endfrag)\s*\k<id>#{TagEnd}
/xom

Instance Method Summary collapse

Instance Method Details

#clean_fragment(body) ⇒ Object



66
67
68
69
70
71
# File 'lib/jekyll-dry.rb', line 66

def clean_fragment(body)
  pattern = /\s*#{FragmentSubPattern}\s*/om
  clean_body = body.gsub(FragmentSubPattern, "")
  clean_body.lstrip!
  clean_body.rstrip!
end

#generate(site) ⇒ Object



30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
# File 'lib/jekyll-dry.rb', line 30

def generate(site)
  # Initialize hash map that will store the fragments for rendering
  class << site
    attr_accessor :fragments
  end
  site.fragments = Hash.new

  # Parse fragments on pages
  site.pages.each do |page|
    fragments = parse_page(page.content)

    site.fragments.merge!(fragments) do |key, old_val, new_val|
      # This section is invoked every time there is a duplicate key
      # in site.fragments and parsed fragments
      raise Liquid::SyntaxError.new(
        "Duplicate fragment #{key} on page #{page.url}",
        original_fragment: old_val,
        duplicate_fragment: new_val
      )
    end
  end
end

#parse_page(content) ⇒ Object



53
54
55
56
57
58
59
60
61
62
63
64
# File 'lib/jekyll-dry.rb', line 53

def parse_page(content)
  fragments = Hash.new

  pos = 0
  while m = FullFragmentPattern.match(content, pos)
    body = clean_fragment(m[:body])
    fragments.store(m[:id], body)
    puts("fragment #{m[:id]}:", body)
    pos = m.begin(:id)
  end
  fragments
end