DEV Community

Discussion on: Help Me Refactor dev.to's Markdown Service!

Collapse
 
hanachin profile image
Seiei Miyagi

refine the String class then just chaining methods at fix_all

class MarkdownFixer < Struct.new(:markdown)
  using Module.new {
    refine(String)do
      def add_quotes_to_title
        gsub('title', '"title"')
      end

      def add_quotes_to_published
        gsub("\r\npublished: ", "\"\r\npublished: ")
      end

      # This turns --- into ------- after the first two,
      # because --- messes with front matter
      def modify_hr_tags
        gsub(/^---/).with_index { |m, i| i > 1 ? "#{m}-----" : m }
      end

      def convert_newline
        gsub("\r\n", "\n")
      end

      def modify_tags
        gsub(/\ntags:.*\n/) do |tags|
          tags.split(" #").join(",").gsub("#", "").gsub(":,", ": ")
        end
      end
    end
  }

  def fix_all
    markdown
      .add_quotes_to_title
      .modify_hr_tags
      .convert_newline
      .add_quotes_to_title
      .add_quotes_to_published
      .moidfy_tags
  end
end