Skip to content

Instantly share code, notes, and snippets.

@maximebf maximebf/drafts.rb
Created Nov 24, 2012

Embed
What would you like to do?
Draft plugin for jekyll
# Search for posts in _drafts folder
#
# Add "drafts: true" in your config file to
# activate the plugin
#
# Filenames should not have a date
# eg: _drafts/my-future-posts.md
#
# Draft posts will have a post.draft property
#
module Jekyll
class Draft < Post
MATCHER = /^(.+\/)*(.*)(\.[^.]+)$/
def self.valid?(name)
name =~ MATCHER
end
def initialize(site, source, dir, name)
@site = site
@base = File.join(source, dir, '_drafts')
@name = name
self.categories = dir.split('/').reject { |x| x.empty? }
self.process(name)
self.read_yaml(@base, name)
#If we've added a date and time to the yaml, use that instead of the filename date
#Means we'll sort correctly.
if self.data.has_key?('date')
# ensure Time via to_s and reparse
self.date = Time.parse(self.data["date"].to_s)
end
if self.data.has_key?('published') && self.data['published'] == false
self.published = false
else
self.published = true
end
self.tags = self.data.pluralized_array("tag", "tags")
if self.categories.empty?
self.categories = self.data.pluralized_array('category', 'categories')
end
self.data['draft'] = true
end
def process(name)
m, cats, slug, ext = *name.match(MATCHER)
self.date = Time.new()
self.slug = slug
self.ext = ext
rescue ArgumentError
raise FatalException.new("Post #{name} does not have a valid filename.")
end
end
class DraftGenerator < Generator
safe true
def generate(site)
if site.config['drafts']
self.read_directories(site)
end
end
def read_directories(site, dir = '')
base = File.join(site.source, dir)
entries = Dir.chdir(base) { site.filter_entries(Dir.entries('.')) }
self.read_drafts(site, dir)
entries.each do |f|
f_abs = File.join(base, f)
f_rel = File.join(dir, f)
if File.directory?(f_abs)
next if site.dest.sub(/\/$/, '') == f_abs
read_directories(site, f_rel)
end
end
end
def read_drafts(site, dir)
base = File.join(site.source, dir, '_drafts')
return unless File.exists?(base)
entries = Dir.chdir(base) { site.filter_entries(Dir['**/*']) }
entries.each do |f|
if Draft.valid?(f)
post = Draft.new(site, site.source, dir, f)
site.posts << post
post.categories.each { |c| site.categories[c] << post }
post.tags.each { |c| site.tags[c] << post }
end
end
site.posts.sort!
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.