4
\$\begingroup\$

I would greatly appreciate feedback on the enclosed script, which auto-generates a Markdown table of contents for Github-flavoured Markdown, with respect to:

  • Consistency with Ruby idiom & style
  • Any use of bad practices
#!/usr/bin/env ruby

def usage
  puts "Usage: #{$0} FILE.md"
  exit 1
end

class ToCWriter
  def initialize(source_file, top=2, max=4)
    @source_file = source_file
    @top = top
    @max = max
    @c = 1
    @level  = ""
    @header = ""
    @start  = ""
    write
  end

  def write
    puts "#### Table of contents\n\n"

    File.open(@source_file).each_line do |line|
      next unless line.match(/^#/)

      @level, @header = line.match(/^(#+) (.*)/).captures
      next if @header == "Table of contents"
      next if skip?

      ref = header_to_ref
      set_start

      puts "#{@start} [#{@header}](##{ref})"
    end
  end

 private

  def skip?
    len = @level.length
    len < @top || len > @max
  end

  def header_to_ref
    @header
      .gsub(/ /, "-")
      .gsub(/[\.\/,&\()<>-]+/, "-")
      .gsub(/-$/, "")
      .downcase
  end

  def set_start
    len = @level.length
    if len == @top
      @start = "#{@c}."
      @c += 1
    else
      bullet = len % 2 == 0 ? "*" : "-"
      @start = "    " * (len - 2) + bullet
    end
  end
end

usage unless ARGV.length == 1
source_file = ARGV[0]

ToCWriter.new(source_file)
\$\endgroup\$
3
  • \$\begingroup\$ use ' instead of " when you can In fact I suggest you to use rubocop, it will help you with all thoose little things \$\endgroup\$ Commented Sep 6, 2018 at 12:44
  • \$\begingroup\$ I was more interested in higher-level design but I suppose you're right about Rubocop. I'll give it a try on that script. \$\endgroup\$ Commented Sep 6, 2018 at 14:08
  • 1
    \$\begingroup\$ That's why I just posted a comment ;) \$\endgroup\$ Commented Sep 6, 2018 at 14:18

0

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.