Create a gist now

Instantly share code, notes, and snippets.

@bchase /draft.rb
Last active Jun 20, 2016

A Ruby script for creating and publishing Jekyll drafts
#!/usr/bin/env ruby
# create Jekyll drafts and publish them (to `_posts/`)
#############
### USAGE ###
#############
#
# ### 1 - start a new draft ###
# $ ./draft.rb name of new post # -> opens `_drafts/name-of-new-post.md` in vim
#
# ### 2 - list all drafts ###
# $ ./draft.rb
# (1) _drafts/hello-world.md
# (2) _drafts/foo-bar.md
# (3) _drafts/asdf.md
#
# ### 3 - publish a draft to `_posts/` ###
# $ date +"%Y-%m-%d"
# 2016-06-20
# $ ./draft.rb 2 # -> moves `_draft/foo-bar.md` to `_posts/2016-06-20-foo-bar.md`
require 'date'
require 'pathname'
module Kernel
alias :pn :Pathname
end
class Draft
module FileFromTitle
def self.included(base)
base.extend ClassMethods
end
def filepath
@filepath ||= filepath_from_title
end
def hyphenated_title
title.strip.downcase.gsub(/[^a-z0-9]+/, ?-)
end
def filepath_from_title
"_drafts/#{hyphenated_title}.md"
end
def open_in_vim
%x[ vim #{filepath} <`tty` >`tty` ]
end
module ClassMethods
def from_cli_args(args)
new title: args.join(" ")
end
end
end
module ToPost
module ClassMethods
def all
pn('_drafts').children
end
def list_all
all.each.with_index do |file, idx|
puts "(#{idx+1}) #{file}"
end
end
def get_by_num(num)
idx = num.to_i - 1
if path = all[idx]
Draft.new(filepath: path)
else
raise "Draft (#{num}) does not exist"
end
end
end
def self.included(base)
base.extend ClassMethods
end
def publish!
%x[ mv -n "#{filepath}" "#{post_filepath}" ]
post_filepath
end
private
def post_filepath
pn('_posts').join("#{Date.today}-#{filepath.basename}")
end
end
attr_reader :title
def initialize(title: nil, filepath: nil)
@title = title
@filepath = filepath
end
include FileFromTitle
include ToPost
end
if ARGV.empty?
Draft.list_all
elsif num = ARGV[0][/(\d+)/, 1]
Draft.get_by_num(num).publish!
else
Draft.from_cli_args(ARGV).open_in_vim
end
#!/usr/bin/zsh
PORT=5000
nohup bundle exec jekyll serve --watch --drafts --port $PORT &> /dev/null &
google-chrome "http://localhost:$PORT"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment