为 Octopress 添加草稿功能

/

Octopress 默认没有草稿功能,在 _post 目录中保存草稿非常不便,只要有一篇文章处于未完成状态,那么就没办法发布,因为没有人会愿意将一篇未完成的文章展示给读者。有了草稿功能这个问题就解决了,除此之外,还可以很方便的将头脑风暴的产物添加到草稿中,等到以后去逐步成熟完善。下面就为 Octopress 添加草稿功能:

添加新建草稿功能

Rakefile 中定义草稿的存储目录为 _draft,创建新建草稿功能 new_draft

drafts_dir = "_drafts"

#  usage rake new_draft[my-new-draft] or rake new_draft['my new draft']
desc "Begin a new draft in #{source_dir}/#{drafts_dir}"
task :new_draft, :title do |t, args|
  if args.title
    title = args.title
  else
    title = get_stdin("Enter a title for your draft: ")
  end
  raise "### You haven't set anything up yet. First run `rake install` to set up an Octopress theme." unless File.directory?(source_dir)
  mkdir_p "#{source_dir}/#{drafts_dir}"
  filename = "#{source_dir}/#{drafts_dir}/#{title.to_url}.#{new_post_ext}"
  if File.exist?(filename)
    abort("rake aborted!") if ask("#{filename} already exists. Do you want to overwrite?", ['y', 'n']) == 'n'
  end
  puts "Creating new draft: #{filename}"
  open(filename, 'w') do |post|
    post.puts "---"
    post.puts "layout: post"
    post.puts "title: \"#{title.gsub(/&/,'&')}\""
    post.puts "published: false"
    post.puts "comments: true"
    post.puts "categories: "
    post.puts "- "
    post.puts "tags: "
    post.puts "- "
    post.puts "---"
  end
end

添加发布草稿功能

创建草稿发布功能 publish_draft,在发布过程中,对欲发布的草稿进行选择,发布时间为选择提交的即时时间。

#  usage rake publish_draft
desc "Select a draft to publish from #{source_dir}/#{drafts_dir} on the current date."
task :publish_draft do
  drafts = Dir.glob("#{source_dir}/#{drafts_dir}/*.#{new_post_ext}")
  drafts.each_with_index do |draft, index|
    begin
      content = File.read(draft)
      if content =~ /\A^(---\s*$\n)(.*?\n?)^(---\s*$\n?)/m
        data = YAML.load("#{$1}#{$2}")
      end
    rescue => e
      puts "Error reading file #{draft}: #{e.message}"
    rescue SyntaxError => e
      puts "YAML Exception reading #{draft}: #{e.message}"
    end
    puts "[#{index}] #{data['title']}"
  end
  puts "Publish which draft?"
  answer = STDIN.gets.chomp
  if /\d+/.match(answer) and not drafts[answer.to_i].nil?
    mkdir_p "#{source_dir}/#{posts_dir}"
    source = drafts[answer.to_i]
    filename = source.gsub(/#{source_dir}\/#{drafts_dir}\//, '')
    dest = "#{source_dir}/#{posts_dir}/#{Time.now.strftime('%Y-%m-%d')}-#{filename}"
    puts "Publishing post to: #{dest}"
    File.open(source) { |source_file|
      contents = source_file.read
      contents.gsub!(/^published: false$/, "date: #{Time.now.strftime('%Y-%m-%d %H:%M:%S %z')}")
      File.open(dest, "w+") { |f| f.write(contents) }
    }
    FileUtils.rm(source)
  else
    puts "Index not found!"
  end
end

效果图:

publish_draft

Comments