Class: StaticPost::Base

Inherits:
Object
  • Object
show all
Extended by:
ActiveModel::Naming
Defined in:
lib/static_post/base.rb

Constant Summary collapse

FRONTMATTER_CONTENT =
/^\s*---\n+(.*?)\n+---/
FRONTMATTER =
/^\s*---\n+.*?\n+---/

Class Method Summary collapse

Class Method Details

.allObject



9
10
11
# File 'lib/static_post/base.rb', line 9

def all
  @posts || load_posts
end

.compile(content) ⇒ Object



29
30
31
32
# File 'lib/static_post/base.rb', line 29

def compile(content)
  @compiler = Redcarpet::Markdown.new(SETTINGS[:renderer])
  @compiler.render(content)
end

.create_record(file, id) ⇒ Object



46
47
48
49
50
51
# File 'lib/static_post/base.rb', line 46

def create_record(file, id)
  {
    id: id,
    attributes: extract_attributes(file)
  }
end

.default_post_pathObject



21
22
23
24
25
26
27
# File 'lib/static_post/base.rb', line 21

def default_post_path
  if defined?(Rails)
    File.expand_path('app/views/posts', Rails.root)
  else
    File.expand_path('.')
  end
end

.extract_attributes(file) ⇒ Object



53
54
55
56
57
58
# File 'lib/static_post/base.rb', line 53

def extract_attributes(file)
  file_content = File.read(file)
  {
    content: post_content(file_content)
  }.merge(extract_frontmatter(file_content))
end

.extract_frontmatter(content) ⇒ Object



60
61
62
63
64
65
66
67
68
# File 'lib/static_post/base.rb', line 60

def extract_frontmatter(content)
  frontmatter = content.match(FRONTMATTER_CONTENT).captures
  if frontmatter.any?
    attributes = YAML.load(frontmatter.first)
    Hash[attributes.map { |k, v| [k.to_sym, v] }]
  else
    {}
  end
end

.load_postsObject



34
35
36
37
38
# File 'lib/static_post/base.rb', line 34

def load_posts
  @posts = post_files.map do |file, i|
    create_record(file, i)
  end
end

.post_content(content) ⇒ Object



70
71
72
# File 'lib/static_post/base.rb', line 70

def post_content(content)
  compile(content.sub(FRONTMATTER, ''))
end

.post_filesObject



40
41
42
43
44
# File 'lib/static_post/base.rb', line 40

def post_files
  Dir.entries("#{@post_path}").select do |file|
    file unless File.directory?(file)
  end
end

.post_path(path = nil) ⇒ Object



13
14
15
16
17
18
19
# File 'lib/static_post/base.rb', line 13

def post_path(path = nil)
  if path.nil?
    @post_path.nil? ? default_post_path : @post_path
  else
    @post_path = File.expand_path(path)
  end
end