Class: Cheepub::Content

Inherits:
Object
  • Object
show all
Includes:
Enumerable
Defined in:
lib/cheepub/content.rb

Constant Summary collapse

SEPARATOR_PATTERN =
/\n\n(?:\={3,}|\-{6,})\s*\n\n/m
FRONTMATTER_PATTERN =
/\A---$(.*?)^---\n/m

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(content) ⇒ Content

Returns a new instance of Content.



16
17
18
19
20
# File 'lib/cheepub/content.rb', line 16

def initialize(content)
  @content = content
  @header, @body = parse_frontmatter(@content)
  @pages = separate_pages(@body)
end

Instance Attribute Details

#bodyObject (readonly)

Returns the value of attribute body.



13
14
15
# File 'lib/cheepub/content.rb', line 13

def body
  @body
end

#headerObject (readonly)

Returns the value of attribute header.



12
13
14
# File 'lib/cheepub/content.rb', line 12

def header
  @header
end

#pagesObject (readonly)

Returns the value of attribute pages.



14
15
16
# File 'lib/cheepub/content.rb', line 14

def pages
  @pages
end

#srcObject (readonly)

Returns the value of attribute src.



11
12
13
# File 'lib/cheepub/content.rb', line 11

def src
  @src
end

Instance Method Details

#eachObject



22
23
24
25
26
# File 'lib/cheepub/content.rb', line 22

def each
  @pages.each do |page|
    yield page
  end
end

#parse_frontmatter(src) ⇒ Object



44
45
46
47
48
49
50
51
52
# File 'lib/cheepub/content.rb', line 44

def parse_frontmatter(src)
  header = body = nil
  if src =~ FRONTMATTER_PATTERN
    header, body = YAML.safe_load($1).symbolize_keys!, $'
  else
    header, body = Hash.new(), src
  end
  return header, body
end

#separate_pages(body) ⇒ Object



29
30
31
32
33
34
35
36
37
38
39
40
41
42
# File 'lib/cheepub/content.rb', line 29

def separate_pages(body)
  pages = nil
  if body =~ SEPARATOR_PATTERN
    pages = body.split(SEPARATOR_PATTERN)
  else
    pages = [body]
  end
  pages.each_with_index do |page, idx|
    if idx < pages.size - 1
      page.concat("\n")
    end
  end
  pages
end