happypeter / haoduoshipin

好多视频
http://haoduoshipin.com
236 stars 88 forks source link

导入 shownote #333

Closed happypeter closed 9 years ago

happypeter commented 9 years ago

从 happycasts.github.io 中的个股文件中,导入到 episode.note 字段中。

不过先要做一些处理:

删除


---
layout: shownote
title: Vagrant

---

kramdown 转换为 redcarpet 的语法

{% highlight ruby %}
config.vm.provider "virtualbox" do |v|
  v.memory = 2048
end
{% endhighlight %}

改为

```ruby
xxxx
billie66 commented 9 years ago
ok
happypeter commented 9 years ago

先用 conver.rb 来把 *.md 文件中的不想要的内容替换掉

Dir["./*.md"].each do |f|
  s = ''
  if f.include?('-')
    File.open(f, 'r') do |file|
      s = file.read.sub(/^layout: shownote/, '').
        sub(/^---\n\n?title: .*?\n---\n/, '').
        gsub(/\{% highlight (.*?) %\}/, '```\1').
        gsub(/\{% endhighlight %\}/, '```').
        gsub(/\n{3,}/, "\n\n")
    end

    File.open(f, 'w') do |file|
      file.write(s.strip)
    end
  end

然后用 lib/tasks/shownote.rake

# encoding: UTF-8
namespace :db do
  desc "import data to the shownote field of episodes table"
  task :shownote => :environment do
    Dir["note/*.md"].each do |f|
      id = f.split('/').last.split('-').first.sub(/^0*/, '')

      File.open(f, 'r') do |file|
        e = Episode.find(id)
        e.note = file.read
        e.save
      end
    end
  end
end

来把 note/*.md 中的数据导入到数据库 Episode.note 字段中。