DEV Community

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

Collapse
 
rhymes profile image
rhymes • Edited

This is my favorite one for now :D

class MarkdownFixer4
  class << self
    def fix_all(markdown)
        methods = [:add_quotes_to_title, :modify_hr_tags, :convert_newlines, :split_tags]
        methods.inject(markdown){|result, method| self.send(method, result) }
    end

    def add_quotes_to_title(markdown)
        markdown.gsub('title', '"title"')
    end

    def modify_hr_tags(markdown)
        markdown.gsub('hr', 'hhr')
    end

    def convert_newlines(markdown)
        markdown.gsub('\r\n', '\n')
    end

    def split_tags(markdown)
        markdown.gsub('tags', 't a g s')
    end
  end
end

puts MarkdownFixer4.fix_all('title hr tags\r\n')

This line methods.inject(markdown){|result, method| self.send(method, result) } calls each method in the array passing the result of the previous method the following one, with markdown as the initial value.

Collapse
 
user_name profile image
User_name

Love these smaller methods.

Easy to read && easy to follow.

Learned some neat refactoring tips-- thanks!

Collapse
 
andy profile image
Andy Zhao (he/him)

Hmmmmm this one is pretty great! I like the use inject a lot. Thanks a lot for the answers! I'm going to think it over on my commute home. :)