Module: CodeButler

Defined in:
lib/codebutler.rb

Constant Summary collapse

SUPPORTED_LANGUAGES =
{
  '.rb'     => :ruby,
  '.c'      => :c,
  '.cc'     => :c,
  '.h'      => :c,
  '.html'   => :html,
  '.rhtml'  => :rhtml,    
}

Class Method Summary collapse

Class Method Details

.clean_argvObject

Ignore all command line arguments except -p

Also clears ARGV to prevent sinatra from parsing



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

def self.clean_argv
  if ARGV.include? "-h"
    puts "    Supported Arguments:\n      -h        Print help (You're looking at it)\n      -p port   Start the webserver on the specified port\n    HELP\n    exit\n  elsif ARGV.include?(\"-p\") && ARGV[ARGV.index(\"-p\") + 1] =~ /^[0-9]+$/\n    port = ARGV[ARGV.index(\"-p\") + 1]\n    ARGV.clear\n    ARGV.unshift ['-p', port.to_s]\n  else\n    ARGV.clear\n  end        \nend\n"

.serveObject

Scan the current working directory for files, and serve them on localhost



40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
# File 'lib/codebutler.rb', line 40

def self.serve
  clean_argv
  
  # Create a regex that matches all supported file endings
  regex = Regexp.new("(#{SUPPORTED_LANGUAGES.keys.map{|key| Regexp.escape(key)}.join('|')})$")
  
  working_dir = Dir.getwd
  file_list = []

  Find.find(working_dir) do |path|
    if match = path.match(regex)
      relative_path = path.slice( working_dir.length..-1 )
      
      file_list << relative_path
      
      # use Sinatra for easy hosting
      # We need to escape the path to catch names like "c++test.rb" and spaces
      get(Regexp.escape(URI.escape(relative_path))) do
        CodeRay.scan(File.readlines(path).join, SUPPORTED_LANGUAGES[match[1]]).div
      end
    end
  end
  
  # index:
  get('/') do
    file_list.sort.map { |file|
      %Q(<a href="#{file}">#{file}</a>)
    }.join("<br/>")      
  end
  
end