Skip to content

Instantly share code, notes, and snippets.

@webuilder240
Created June 18, 2020 12:00
Show Gist options
  • Save webuilder240/ccdddc97798b9bcc1d4124a661ba5301 to your computer and use it in GitHub Desktop.
Save webuilder240/ccdddc97798b9bcc1d4124a661ba5301 to your computer and use it in GitHub Desktop.
class MtParser
attr_reader :mt_records, :file_path, :is_parseing_body
def self.import
parser = new("#{Rails.root}/app/models/webuilder240.hatenablog.com.export.txt")
parser.parse
records = parser.mt_records
ActiveRecord::Base.transaction do
records.each do |mt_record|
Blog.create!(
title: mt_record.title,
content: mt_record.body,
is_publish: mt_record.status == "Publish",
first_published_at: mt_record.date
)
end
end
end
def initialize(file_path)
@file_path = file_path
@mt_records = []
@is_parseing_body = false
end
def parse
open(file_path) do |file|
@current_record = MtRecord.new()
file.each_line do |line|
if line == MtRecord::POST_PERIOD
@mt_records << @current_record
@current_record = MtRecord.new()
next
end
if @is_parseing_body
if line == MtRecord::SECTION_PERIOD
@is_parseing_body = false
else
current_record.body << line
end
next
end
MtRecord::MT_ATTRIBUTES.each do |mt_attr|
if line =~ /^#{mt_attr}\:/
if mt_attr == "BODY"
@is_parseing_body = true
current_record.body = ""
else
line.chomp!
line.gsub!(/^#{mt_attr}\: /, "")
current_record.send("#{mt_attr.downcase}=", line)
end
end
end
end
end
end
private
attr_reader :current_record
end
class MtRecord
MT_ATTRIBUTES = %W(TITLE AUTHOR STATUS DATE BODY)
POST_PERIOD = "--------\n"
SECTION_PERIOD = "-----\n"
attr_accessor :title, :author, :base_name, :date, :body, :status
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment