Class: Pressy::PostParser

Inherits:
Object
  • Object
show all
Defined in:
lib/pressy/post_parser.rb

Overview

PostParser transforms the contents of a rendered post into a Pressy::Post.

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(params) ⇒ PostParser

Creates a new parser for a rendered post.

Parameters:

  • params (Hash)

    a customizable set of options

Options Hash (params):

  • :format (String)

    The format of the WordPress post

  • :content (IO, String)

    The rendered content of the post



14
15
16
17
18
19
# File 'lib/pressy/post_parser.rb', line 14

def initialize(params)
  @format = params.fetch(:format)
  @content = params.fetch(:content)

  @content = StringIO.new(@content) if @content.is_a? String
end

Instance Attribute Details

#contentIO (readonly)

Returns the rendered content of the post to parse

Returns:

  • (IO)

    the rendered content of the post to parse



9
10
11
# File 'lib/pressy/post_parser.rb', line 9

def content
  @content
end

#formatString (readonly)

Returns the format of the post, derived from the directory the post is stored in

Returns:

  • (String)

    the format of the post, derived from the directory the post is stored in



7
8
9
# File 'lib/pressy/post_parser.rb', line 7

def format
  @format
end

Class Method Details

.parse(params) ⇒ Pressy::Post

Note:

Equivalent to Pressy::PostParser.new(params).parse

Creates a new parser with the given parameters, and returns the parsed post.

Parameters:

  • params (Hash)

    a customizable set of options

Options Hash (params):

  • :format (String)

    The format of the WordPress post

  • :content (IO, String)

    The rendered content of the post

Returns:

  • (Pressy::Post)

    The post parsed from the given content



42
43
44
# File 'lib/pressy/post_parser.rb', line 42

def self.parse(params)
  self.new(params).parse
end

Instance Method Details

#parsePressy::Post

Parses the rendered post into a Pressy::Post.

Returns:

  • (Pressy::Post)

    The post parsed from the given content



23
24
25
26
27
28
29
30
31
32
33
34
35
36
# File 'lib/pressy/post_parser.rb', line 23

def parse
  return Pressy::Post.new("post_content" => "", "post_format" => format) if lines.empty?

  if lines.first.strip == "---"
    the_lines = lines.drop(1)
    frontmatter_end_idx = the_lines.index { |line| line.strip == "---" }
    frontmatter_lines = the_lines[0...frontmatter_end_idx]
    params = parse_frontmatter(frontmatter_lines)
    content = the_lines[(frontmatter_end_idx + 1)..-1]
    Pressy::Post.new(params.merge("post_content" => content.join(""), "post_format" => format))
  else
    Pressy::Post.new("post_content" => lines.join(""), "post_format" => format)
  end
end