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

« Newer Snippets
Older Snippets »
Showing 1-9 of 9 total  RSS 

Creating a simple Ruby Class documenter

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>

Generate Ruby code using XML and XSL

This XSL code transforms an XML file into a basic Ruby file. See the previous post ('Transforming an XML file into an XSL file' http://snipr.com/1usrh [dzone.com]) for an example of the XML used.

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
<xsl:output method="text"/>

  <xsl:template match="recordx">
  <xsl:variable name="project" select="summary/project" />
  <xsl:variable name="parent_element" select="summary/parent_element" />
  <xsl:text>#!/usr/bin/ruby
#file: </xsl:text><xsl:value-of select="$project"/><xsl:text>.rb

require 'recordx'

class </xsl:text><xsl:value-of select="$project"/><xsl:text> &lt; RecordX

  def initialize()
    @project = "</xsl:text><xsl:value-of select="$project"/><xsl:text>"
    @parent_element = '</xsl:text><xsl:value-of select="$parent_element"/><xsl:text>fields'
    @proj = Projxml.new
    @doc_vrecord = initialize_xml_class(SERVER_URL + '/' + @project + '/class_template.xml')
    @doc_file = get_doc()
  end
  
end

if __FILE__ == $0
    r = </xsl:text><xsl:value-of select="$project"/><xsl:text>.new()
end
  </xsl:text>
  </xsl:template>
  
</xsl:stylesheet>

Transforming an XML file into an XSL file

This XSL uses the XML for creating another XSL file which renders a web page containing records for a specific project, but I have found the projects I am working on use similar page layouts (ie. menu, body(articles), inputs, and buttons), so it makes sense to re-use a generic template.

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">

  <xsl:template match="recordx">
    <xsl:variable name="colon"><xsl:text>:</xsl:text></xsl:variable>
    <xsl:element name="xsl:stylesheet">
      <xsl:attribute name="xmlns{$colon}xsl">
        <xsl:text>http://www.w3.org/1999/XSL/Transform</xsl:text>
      </xsl:attribute>
      <xsl:attribute name="version">
        <xsl:text>1.0</xsl:text>
      </xsl:attribute>
      <xsl:element name="xsl:template">
      <xsl:attribute name="match">
        <xsl:value-of select="summary/project"/><xsl:text>page</xsl:text>
      </xsl:attribute>
      <xsl:copy-of select="menu/*"/>
      <xsl:copy-of select="articles/*"/>
      </xsl:element>
      <xsl:element name="xsl:template">
        <xsl:attribute name="match">
          <xsl:value-of select="summary/project"/><xsl:text>page/inputs</xsl:text>
      </xsl:attribute>
      <xsl:element name="div">
        <xsl:element name="dl"> 
          <xsl:for-each select="records/fields">
            <xsl:if test="c='true'">
              <xsl:element name="xsl:apply-templates">
                <xsl:attribute name="select"><xsl:copy-of select="field"/></xsl:attribute>
              </xsl:element>
            </xsl:if>
          </xsl:for-each>
        </xsl:element>
      </xsl:element>
      </xsl:element>      
      <xsl:call-template name="inputx" />      
    </xsl:element>
  </xsl:template>
  
  <xsl:template name="inputx">
    <xsl:apply-templates select="records/fields"/>
  </xsl:template>
  
  <xsl:template match="records/fields">
    <xsl:if test="c='true'">
    <xsl:element name="xsl:template">
      <xsl:attribute name="match"><xsl:value-of select="field"/></xsl:attribute>
        <dt>
          <xsl:element name="label">
            <xsl:attribute name="for"><xsl:text>title</xsl:text></xsl:attribute>
            <xsl:element name="xsl:value-of">
              <xsl:attribute name="select"><xsl:text>@title</xsl:text></xsl:attribute>
            </xsl:element>
          </xsl:element>
        </dt>
        <dd>
          <xsl:element name="input">
            <xsl:attribute name="type"><xsl:text>text</xsl:text></xsl:attribute>
            <xsl:attribute name="id"><xsl:text>title</xsl:text></xsl:attribute>
            <xsl:attribute name="size"><xsl:text>{@size}</xsl:text></xsl:attribute>            
          </xsl:element>
        </dd>
    </xsl:element>
    </xsl:if>
  </xsl:template>
  
</xsl:stylesheet>


... and here's the XML which is used by the XSL above.

<recordx>
<summary><project>books</project><parent_element>book_entry</parent_element></summary>
<menu>
  <div id="gboxes">
    <ul>
      <li><a href="/empsearch/devsearch.xml?id=all">home</a></li> 
      <li><a href="/main/development_blog.xml">development</a></li>
    </ul>
  </div>
</menu>
<articles>
  <div id="articles">
    <h1>www<xsl:value-of select="@title" /></h1>
    <div>
      <xsl:apply-templates select="inputs"></xsl:apply-templates>
    </div>
    <div>
      <xsl:apply-templates select="buttons"></xsl:apply-templates>
    </div>
    <span id="in1"></span>
  </div> 
</articles>
<records>
<fields id='17647'><field>author</field><c>true</c><r>true</r><u>true</u></fields>
<fields id='17675'><field>subject</field><c>true</c><r>true</r><u>false</u></fields>
<fields id='17699'><field>rating</field><c/><r/><u/></fields>
<fields id='17700'><field>last_modified</field><c/><r/><u/></fields>
</records>
</recordx>


PHP password generator

This is a random php password generator. This function is a complete, working password generator implementation for PHP. It allows the developer to customize the password: set password length and strength. Just include this function anywhere in your code and then use it.

More code snippets you can find on free code and tutorials website.

function generatePassword($length=9, $strength=0) {
    $vowels = 'aeuy';
    $consonants = 'bdghjmnpqrstvz';
    if ($strength & 1) {
        $consonants .= 'BDGHJLMNPQRSTVWXZ';
    }
    if ($strength & 2) {
        $vowels .= "AEUY";
    }
    if ($strength & 4) {
        $consonants .= '23456789';
    }
    if ($strength & 8) {
        $consonants .= '@#$%';
    }

    $password = '';
    $alt = time() % 2;
    srand(time());
    for ($i = 0; $i < $length; $i++) {
        if ($alt == 1) {
            $password .= $consonants[(rand() % strlen($consonants))];
            $alt = 0;
        } else {
            $password .= $vowels[(rand() % strlen($vowels))];
            $alt = 1;
        }
    }
    return $password;
}

rails generator syntax

// generate application
rails projectname


// generate migration.
ruby script/generate migration migration_name
ruby script/generate migration add_price


// generate model
// we can give a list of columns and types
// :string, :text, :integer, :decimal, :float, :date, ...
ruby script/generate model model_name
ruby script/generate model user name:string hashed_password:string salt:string


// generate controller
ruby script/generate controller controller_name method_name(s)
ruby script/generate controller store index


// generate scaffold
ruby script/generate scaffold model_name controller_name
ruby script/generate scaffold product admin

Generate Rails fixture skeleton using ActiveRecord

In Rails 1.1.5, the basic generator generates the following code for the fixture used in database unit tests:
# Read about fixtures at http://ar.rubyonrails.org/classes/Fixtures.html
first:
  id: 1
another:
  id: 2


As ActiveRecord provides database reflexion features, we can generate a fixture file with all the columns' name prepopulated for number and text types, such as:
# Read about fixtures at http://ar.rubyonrails.org/classes/Fixtures.html
first:
  id: 1
  short_title: short_title_first
  title: title_first


This will be done by the following class:
require_gem 'activerecord'

class RailsFixturesGenerator

  def generate(class_name)
    
    # Get the "Class" object from the class name        
    model_class = Object.const_get(class_name)
    
    yaml_content =  "# Read about fixtures at http://ar.rubyonrails.org/classes/Fixtures.html\n"
    yaml_content += "first:\n"
    
    # get if first!   
    model_class.columns.each { |column|
      
      yaml_content += "  " + column.name + ": "
      
      if column.number?
        yaml_content +=  "1"
      end
      if column.text?
        # @todo /!\ max length
        yaml_content +=  column.name + "_first"
      end
      
      yaml_content += "\n"      
    }  
    
    write_fixture_file(model_class, yaml_content)
    
    yaml_content            
  end  
  
  # Write the <fixture> yaml file  in the test/fixtures folder
  def write_fixture_file(model_class, yaml_content)
    
    path = ENV['DEST'] || "#{RAILS_ROOT}/test/fixtures"
    db   = ENV['DB']   || 'test'
    
    File.open("#{path}/#{model_class.table_name}.yml", 'wb') do |file|    
      file.write yaml_content 
      file.close    
    end
  end
end


Of course, I have an unit test that I wrote before the code ;-)
This was my first "complex" method I wrote in Ruby so please bear with me. Any feedback is welcome. I want to write a Rails plugin in order to share the generators I will write.

Another Pyrex Permutation Generator

// description of your code here

cdef class PermuteJ:

   cdef int n, first
   cdef int lst3[32]
   cdef object lst, lst2

   def __init__(self, lst):
       cdef int i
       self.lst = lst
       self.lst2 = lst[:]
       self.first = 0
       self.n = len(lst) - 1
       if self.n >= 31:
           raise Exception, "Are you kidding?"
       for i from 0 <= i < len(lst):
           self.lst3[i] = i

   def __iter__(self):
       return self

   def __next__(self):
       cdef int j, l, k, x, y, z, sn, length, neg1, neg2, neg3
       cdef int* sl
       cdef object output

       if self.first == 0:
           self.first = 1
           return self.lst2
       if self.n == 1:
           return [self.lst[1], self.lst[0]]

       sn = self.n
       length = sn + 1
       sl = self.lst3
       neg1 = sn
       neg2 = length - 2
       neg3 = length - 3
       while 1:
           if sl[neg2] < sl[neg1]:
               sl[neg2], sl[neg1] = sl[neg1], sl[neg2]
           elif sl[neg3] < sl[neg2]:
               if sl[neg3] < sl[neg1]:
                   sl[neg3], sl[neg2], sl[neg1] = sl[neg1], sl[neg3], sl[neg2]
               else:
                   sl[neg3], sl[neg2], sl[neg1] = sl[neg2], sl[neg1], sl[neg3]
           else:
               j = sn - 3
               if j < 0: raise StopIteration
               y = sl[j]
               x = sl[neg3]
               z = sl[neg1]
               while y >= x:
                   j = j - 1
                   if j < 0: raise StopIteration
                   x = y
                   y = sl[j]
               if y < z:
                   sl[j] = z
                   sl[j+1] = y
                   sl[sn] = x
               else:
                   l = neg2
                   while y >= sl[l]:
                       l = l - 1
                   sl[j], sl[l] = sl[l], y
                   sl[sn], sl[j+1] = sl[j+1], sl[sn]
               k = j + 2
               l = neg2
               while k < l:
                   sl[k], sl[l] = sl[l], sl[k]
                   k = k + 1
                   l = l - 1

           lst = self.lst
           lst2 = self.lst2
           for j from 0 <= j < length:
               lst2[j] = sl[j]

           return lst2

gen-sym

REBOL [
    Title: "Unique symbol generator"
]

gen-sym-ctx: context [
    prefix: "&"
    counter: 0
    clear: does [counter: 0]
    set-prefix: func [value] [prefix: form value]
    set 'gen-sym does [
        counter: counter + 1
        to word! join prefix counter
    ]
]

repeat i 5 [print gen-sym]
gen-sym-ctx/set-prefix 'G
gen-sym-ctx/clear
repeat i 5 [print gen-sym]

Generate all permutation of a list

From Michael Davies's recipe.
def all_perms(str):
    if len(str) <=1:
        yield str
    else:
        for perm in all_perms(str[1:]):
            for i in range(len(perm)+1):
                yield perm[:i] + str[0:1] + perm[i:]

Some example usage
>>> for p in all_perms(['a','b','c']):
	print p

['a', 'b', 'c']
['b', 'a', 'c']
['b', 'c', 'a']
['a', 'c', 'b']
['c', 'a', 'b']
['c', 'b', 'a']

A great use of generator and recursive call.
« Newer Snippets
Older Snippets »
Showing 1-9 of 9 total  RSS