Never been to DZone Snippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Creating a simple Ruby Class documenter (See related posts)

This Ruby code stores the class name, method names, and method parameters from a ruby file in an XML file. I have a habit of forgetting what methods I use in my classes, with this code I should at least be able to build up a quick class browser.

#!/usr/bin/ruby

# file: ruby2xml.rb

require 'rexml/document'
include REXML

class Ruby2XML

  attr :doc
  
  def initialize(buffer)

    @outline = buffer.scan(/^class\s+(\w+)(\s+)?|def\s+(\w+)(\s+)?\(?(.*(?=\)))?/)
    @doc = Document.new
    @doc.add_element('ruby')
    o_class = Element.new('class')
    o_class.add_attribute('name', get_class_name)
    o_methods = Element.new('methods')
    
    #get the methods
    1.upto(get_method_count) {|i| o_methods.add_element(add_method(@outline[i])) }
    o_class.add_element(o_methods)
    @doc.root.add_element o_class

  end
  
  private # everything below this point is private
  
  def get_class_name()
    @outline[0][0]
  end
  
  def get_method_count
    mc = -1
    @outline.each {|m| mc += 1}
    mc 
  end
  
  def add_method(amethod)
    o_method = Element.new('method')
    o_method.add_attribute('name',amethod[2]) #get the method name
    o_params = Element.new('params')

    if amethod[4] then # get the parameter names
      amethod[4].split(',').each {|a| o_params.add_element(add_param(a.strip))}
    end
    
    o_method.add_element(o_params)    
    o_method
  end
  
  def add_param(param)
    o_param = Element.new('param')
    o_param.text = param
    o_param
  end
      
end

if __FILE__ == $0

  buffer = File.new('ruby2xml.rb').read
  rx2 = Ruby2XML.new(buffer)
  
  file = File.new('ruby2xml.xml','w')
  file.puts rx2.doc
  file.close

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
<ruby>
  <class name='Ruby2XML'>
    <methods>
      <method name='initialize'><params><param>buffer</param></params></method>
      <method name='get_class_name'><params/></method>
      <method name='get_method_count'><params/></method>
      <method name='add_method'><params><param>amethod</param></params></method>
      <method name='add_param'><params><param>param</param></params></method>
    </methods>
  </class>
</ruby>

Comments on this post

sumantacaptain posts on Apr 11, 2008 at 08:20
i cant understand the program fully
can any body give me any suggession to me about this
how can i increase the nodes & how can i change those names...etc

You need to create an account or log in to post comments to this site.


Click here to browse all 4852 code snippets

Related Posts