Jekyll:最简单的rakefile来创建新帖子

emh*_*emh 4 ruby rake jekyll

我刚开始使用jekyll(我是新手ruby)并且我正在尝试创建一个rakefile来自动创建帖子.

我想键入类似的内容:rake post title="x"并创建一个带有该标题和今天日期的帖子.

现在我正在看着这个rakefile,jekyll bootstrap但它看起来像我想要的东西.

我把它切成:

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
Run Code Online (Sandbox Code Playgroud)

但也许有一种更清洁的方法来解决这个问题.

问题:这可以进一步简化,还是有更好的方法来做我想做的事情?

afr*_*iro 10

如果你(或任何人)仍然感兴趣,一个非常小的rakefile可能是:

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
Run Code Online (Sandbox Code Playgroud)

取自这里.

  • 我也想在帖子中添加日期:'''日期:#{Time.now.strftime('%Y-%m-%d%H:%M')}''' (2认同)

ran*_*ibt 6

好吧,你可以只使用Jekyll Compose Plugin。它工作得很好。

bundle init
Run Code Online (Sandbox Code Playgroud)

添加

gem 'jekyll-compose', group: [:jekyll_plugins]
Run Code Online (Sandbox Code Playgroud)

到您的 Gemfile。

bundle
Run Code Online (Sandbox Code Playgroud)

最后,运行插件命令来管理您的页面和帖子。