Question

I just started using jekyll (I am new to ruby) and am trying to create a rakefile to automate the creation of posts.

I want to type something like: rake post title="x" and have it create a post with that title and today's date.

Right now I am looking at the rakefile from jekyll bootstrap but it seems like overkill for what I want.

I cut it down to:

require 'rake'
require 'yaml'

SOURCE = "."
CONFIG = {
  'posts' => File.join(SOURCE, "_posts"),
  'post_ext' => "md",
}

# Usage: rake post title="A Title"
desc "Begin a new post in #{CONFIG['posts']}"
task :post do
  abort("rake aborted: '#{CONFIG['posts']}' directory not found.") unless FileTest.directory?(CONFIG['posts'])
  title = ENV["title"] || "new-post"
  slug = title.downcase.strip.gsub(' ', '-').gsub(/[^\w-]/, '')
  filename = File.join(CONFIG['posts'], "#{Time.now.strftime('%Y-%m-%d')}-#{slug}.#{CONFIG['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 post: #{filename}"
  open(filename, 'w') do |post|
    post.puts "---"
    post.puts "layout: post"
    post.puts "title: \"#{title.gsub(/-/,' ')}\""
    post.puts "category: "
    post.puts "tags: []"
    post.puts "---"
  end
end # task :post

But maybe there is a cleaner way to go about this.

Question: can this be simplified further or is there a better way to do what I am trying to do?

Was it helpful?

Solution

If you (or anyone) is still interested, a quite minimal rakefile could be:

require 'time'

desc 'create a new draft post'
task :post do
    title = ENV['TITLE']
    slug = "#{Date.today}-#{title.downcase.gsub(/[^\w]+/, '-')}"

    file = File.join(
        File.dirname(__FILE__),
        '_posts',
        slug + '.markdown'
    )

    File.open(file, "w") do |f|
        f << <<-EOS.gsub(/^     /, '')
        ---
        layout: post
        title: #{title}
        published: false
        categories:
        ---

        EOS
    end

    system ("#{ENV['EDITOR']} #{file}")
end

Taken from here.

OTHER TIPS

Well, you could just use the Jekyll Compose Plugin. It works pretty well.

Run

bundle init

add

gem 'jekyll-compose', group: [:jekyll_plugins]

to your Gemfile.

Run

bundle

and, finally, run the plugin commands to manage your pages and posts.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top