Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jekyll: simplest possible rakefile to create new post

Tags:

ruby

rake

jekyll

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?

like image 909
e h Avatar asked Mar 27 '14 12:03

e h


1 Answers

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.

like image 198
afrendeiro Avatar answered Sep 28 '22 16:09

afrendeiro