class Dimples::Sources::Base

A base class representing a source file with frontmatter metadata that can be rendered.

Constants

FRONT_MATTER_PATTERN

Attributes

contents[RW]
metadata[RW]
path[RW]

Public Class Methods

new(site, path) click to toggle source
# File lib/dimples/sources/base.rb, line 11
def initialize(site, path)
  @site = site
  @path = File.expand_path(path)

  @metadata = default_metadata
  @contents = File.read(@path)

  parse_metadata(@contents)
  assign_metadata
end

Public Instance Methods

assign_metadata() click to toggle source
# File lib/dimples/sources/base.rb, line 30
def assign_metadata
  @metadata.each_key do |key|
    self.class.send(:define_method, key.to_sym) { @metadata[key] }
  end
end
output_directory() click to toggle source
# File lib/dimples/sources/base.rb, line 58
def output_directory
  @site.config[:output][:root]
end
parse_metadata(contents) click to toggle source
# File lib/dimples/sources/base.rb, line 22
def parse_metadata(contents)
  matches = contents.match(FRONT_MATTER_PATTERN)
  return unless matches

  @metadata.merge!(YAML.safe_load(matches[1], symbolize_names: true, permitted_classes: [Date]))
  @contents = matches.post_match.strip
end
render(render_metadata = {}, body = nil) click to toggle source
# File lib/dimples/sources/base.rb, line 48
def render(render_metadata = {}, body = nil)
  render_metadata[:site] ||= @site.metadata
  render_metadata[:page] ||= metadata

  output = template.render(Metadata.new(render_metadata)) { body }
  return output unless @metadata[:layout] && @site.layouts[@metadata[:layout]]

  @site.layouts[@metadata[:layout]].render(render_metadata, output)
end
template() click to toggle source
# File lib/dimples/sources/base.rb, line 66
def template
  raise NotImplementedError, 'You must set a Tilt template for this class.'
end
url_for(path) click to toggle source
# File lib/dimples/sources/base.rb, line 62
def url_for(path)
  path.gsub(@site.config[:output][:root], '').concat('/')
end
write(output_path = nil, metadata = {}) click to toggle source
# File lib/dimples/sources/base.rb, line 36
def write(output_path = nil, metadata = {})
  output_path = File.join(output_directory, filename) if output_path.nil?
  output_dir = File.dirname(output_path)

  @metadata[:url] = url_for(output_dir)

  output = render(metadata)

  FileUtils.mkdir_p(output_dir) unless File.directory?(output_dir)
  File.write(output_path, output)
end

Private Instance Methods

default_metadata() click to toggle source
# File lib/dimples/sources/base.rb, line 72
def default_metadata
  {
    layout: nil,
    filename: 'index.html'
  }
end