Creating a simple Ruby Class documenter
1 2 #!/usr/bin/ruby 3 4 # file: ruby2xml.rb 5 6 require 'rexml/document' 7 include REXML 8 9 class Ruby2XML 10 11 attr :doc 12 13 def initialize(buffer) 14 15 @outline = buffer.scan(/^class\s+(\w+)(\s+)?|def\s+(\w+)(\s+)?\(?(.*(?=\)))?/) 16 @doc = Document.new 17 @doc.add_element('ruby') 18 o_class = Element.new('class') 19 o_class.add_attribute('name', get_class_name) 20 o_methods = Element.new('methods') 21 22 #get the methods 23 1.upto(get_method_count) {|i| o_methods.add_element(add_method(@outline[i])) } 24 o_class.add_element(o_methods) 25 @doc.root.add_element o_class 26 27 end 28 29 private # everything below this point is private 30 31 def get_class_name() 32 @outline[0][0] 33 end 34 35 def get_method_count 36 mc = -1 37 @outline.each {|m| mc += 1} 38 mc 39 end 40 41 def add_method(amethod) 42 o_method = Element.new('method') 43 o_method.add_attribute('name',amethod[2]) #get the method name 44 o_params = Element.new('params') 45 46 if amethod[4] then # get the parameter names 47 amethod[4].split(',').each {|a| o_params.add_element(add_param(a.strip))} 48 end 49 50 o_method.add_element(o_params) 51 o_method 52 end 53 54 def add_param(param) 55 o_param = Element.new('param') 56 o_param.text = param 57 o_param 58 end 59 60 end 61 62 if __FILE__ == $0 63 64 buffer = File.new('ruby2xml.rb').read 65 rx2 = Ruby2XML.new(buffer) 66 67 file = File.new('ruby2xml.xml','w') 68 file.puts rx2.doc 69 file.close 70 71 end
Note: This is just my first attempt at building some kind of Ruby code documenter, but it should be good enough for my needs at the moment.
output
1 2 <ruby> 3 <class name='Ruby2XML'> 4 <methods> 5 <method name='initialize'><params><param>buffer</param></params></method> 6 <method name='get_class_name'><params/></method> 7 <method name='get_method_count'><params/></method> 8 <method name='add_method'><params><param>amethod</param></params></method> 9 <method name='add_param'><params><param>param</param></params></method> 10 </methods> 11 </class> 12 </ruby>