Ruby DIY Markdown 切檔代碼

leo424y · 2016年11月05日 · 1539 次阅读

Myblog http://leo424y.github.io

此档案可以将一文字档单档切成 Github Page 用的 Markdown 档案,可方便直推 Github BLOG 如 https://jekyllrb.com/

v1.0.1105

TODO 重构,通用化,对不起它很脏 XD

# 将此档另存后执行 $ ruby spliter.rb 即将同资料夹内的 "-2016-11-05-.md" 切出下面格式档案
# -2016-11-05-.md
# 事实
# 就是一切发生的事,众人认同的事
# xxx
# 情感
# 就是你看一切的看法
#
# 档案一.md
# ---
# layout: post
# comments: true
# title: 事实
# ---
# 就是一切发生的事,众人认同的事
#
# 档案二.md
# ---
# layout: post
# comments: true
# title: 情感
# ---
# 就是你看一切的看法
def chunker(f_in, out_pref)
  # 切档记号
  splitter = 'xxx'

  File.open(f_in, 'r') do |fh_in|
    $title = ''
    filename = 1
    until fh_in.eof?
      unless File.exist?("#{out_pref}#{$title}#{filename}.md")
        File.open("#{out_pref}#{filename}.md", 'w+') do |fh_out|
          $title = fh_in.readline.chomp!
          File.rename("#{out_pref}#{filename}.md", "#{out_pref}#{$title}#{filename}.md")

          head = <<HEAD
---
layout: post
comments: true
title: #{$title}
---
HEAD
          fh_out << head
          puts '写进head'
        end
      end
      puts ">>打开#{filename}.md"
      # File https://www.tutorialspoint.com/ruby/ruby_input_output.htm
      File.open("#{out_pref}#{$title}#{filename}.md", 'a+') do |fh_out|
        line_context = fh_in.readline
        puts '下一行'
        # 碰到splitter开新档案
        if line_context == "#{splitter}\n"
          filename += 1
          puts ">>换至#{filename}.md"
        else
          fh_out << line_context
          puts ">>写进#{line_context}"
        end
      end
    end
  end
end
today = Time.now.to_s.split(' ')[0]

chunker "-#{today}-.md", "#{today}-"
暂无回复。
需要 登录 后方可回复, 如果你还没有账号请 注册新账号