Module: Tocify

Defined in:
lib/tocify.rb,
lib/tocify/version.rb

Constant Summary collapse

VERSION =
"0.0.2"

Class Method Summary collapse

Class Method Details

.filter_args(args) ⇒ Object



4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
# File 'lib/tocify.rb', line 4

def self.filter_args(args)
  # see if we should inject this ToC back into the file
  if args.include?("--inject") || args.include?("-i")
    inject = true
    args.delete("--inject")
    args.delete("-i")
  else
    inject = false
  end
  
  # pass in our file name if we have it
  if args.length > 0
    Tocify.run(args[0], inject)
  else
    Tocify.run(nil, inject)
  end
end

.generate(file_name) ⇒ Object



41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
# File 'lib/tocify.rb', line 41

def self.generate(file_name)
  toc = Array.new
  toc << "## Table of Contents"

  File.open(file_name).each do |line|
    if line.start_with?("##") && line.start_with?(toc[0]) == false
      # count number of lines, figure out how many leading paces we need
      # two spaces for each hash after the second
      spaces = " " * (line.split(" ").first.count("#") - 2) * 4
      title = line.split(" ")
      title.shift
      # links are the title, downcased, and spaces replaced with hyphens
      # also make sure to remove non-alphanumeric characters
      link = title.map {|w| w.downcase } .join("-").delete('^a-zA-Z0-9\-')
      toc << "#{spaces}* [#{title.join(" ")}](##{link})"
    end
  end
  toc.join("\n")
end

.insert(toc, file_name) ⇒ Object



61
62
63
64
65
# File 'lib/tocify.rb', line 61

def self.insert(toc, file_name)
  content = File.read(file_name)
  content.sub!(/(\n## Table of Contents.+?|)\n##/im, "\n" + toc + "\n\n_Generated with [tocify](https://github.com/pyro2927/tocify)_\n\n##")
  File.write(file_name, content)
end

.run(file_name = nil, inject = false) ⇒ Object



21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
# File 'lib/tocify.rb', line 21

def self.run(file_name = nil, inject = false)
  # sanity checks
  if file_name.nil?
    if File.exist?('README.md')
      file_name = 'README.md'
    else
      puts "You must provide a file name"
      return
    end
  elsif File.exist?(file_name) == false
    puts "The file '#{file_name}' doesn't exist"
    return
  end
  toc = Tocify.generate(file_name)
  if inject
    Tocify.insert(toc, file_name)
  end
  toc
end