require "fileutils" require_relative "../core_ext" require "colorize" module Post class Builder def initialize(options:) @options = options end def filepath @options.date ? _filepath_date : _filepath_title end private def _filepath_date "blog/posts/dates/#{@options.date}.md" end private def _filepath_title # topics_amount = File["blog/posts/topics/*"].size # "blog/posts/topics/#{topics_amount}.md" "blog/posts/topics/#{@options.title.slugify}.md" end def input_to_body @options.date ? _input_to_body_date : _input_to_body_title end private def _input_to_body_date @options.input end private def _input_to_body_title "# #{@options.title}\n\n#{@options.input}" end def write! String.disable_colorization true if !@options.colorize filepath = filepath() dirpath = File.dirname filepath FileUtils.mkdir_p dirpath new_body = input_to_body old_body = File.read(filepath) if File.exist?(filepath) body = [old_body, new_body].compact.join("\n---\n\n") # we could use "a" mode for optimisation but it's overkill File.write filepath, body puts "Wrote the file #{filepath}".green puts "Kept the content of the old post".yellow new_lines_amount = new_body.count "\n" puts "Wrote #{new_lines_amount} lines".yellow end end end