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 21-30 of 179 total

Format Ruby code in HTML

This code uses the Ruby gem 'syntax' to create an XML file containing the HTML tags around the code, which is then transformed into an HTML file. The working example was first built using coding examples from Howto format ruby code for blogs [wolfman.com] and Formatting Ruby and HTML code for blog posting [blogspot.com]

   1  
   2  #!/usr/bin/ruby
   3  
   4  #file: ruby2html.rb 
   5  
   6  require 'rubygems'
   7  require 'syntax/convertors/html'
   8  require 'projxslt' # <- this is my own class to do an XSLT transform 
   9  require 'rexml/document'
  10  include REXML
  11  
  12  class Ruby2Html
  13    def initialize(rubyfile, htmlfile)
  14      code = File.read(rubyfile)
  15      convertor = Syntax::Convertors::HTML.for_syntax "ruby"
  16      code_html = convertor.convert(code)
  17      
  18      tempfile = '../temp/ruby2html.xml'
  19      xslfile = '../ruby2html/ruby2html.xsl'
  20      save_file(tempfile, code_html)
  21      
  22      px = Projxslt.new(tempfile, xslfile)
  23      buffer = px.transform()
  24      save_file(htmlfile, buffer)
  25      
  26    end
  27    
  28    def save_file(filename, buffer)
  29      file = File.new(filename, 'w')
  30      file.puts buffer
  31      file.close
  32    end
  33  end
  34  
  35  if __FILE__ == $0
  36    r2h = Ruby2Html.new('ruby2html.rb', '../temp/ruby2html.html')
  37    puts 'completed'
  38  end

file: ruby2html.xsl
   1  
   2  <xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
   3                  xmlns="http://www.w3.org/1999/xhtml"
   4                  version="1.0">
   5  
   6    <xsl:output method="html" doctype-public="-//W3C//DTD XHTML 1.0 Transitional//EN"
   7            doctype-system="http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"
   8            encoding="ISO-8859-1"/> 
   9  
  10  	<xsl:template match="/">
  11  	<xsl:element name="html">
  12  
  13          <head>
  14            <title>Sample code</title>
  15            <link rel="stylesheet" type="text/css" href="ruby2html.css" />
  16  	</head>
  17  
  18  	<body>
  19            <div id="wrap">
  20            <xsl:apply-templates />
  21            </div>
  22  	</body> 
  23  
  24  	</xsl:element>
  25  	</xsl:template>
  26  
  27  	<xsl:template match="pre">
  28  	  <xsl:copy-of select="."/>
  29  	</xsl:template>
  30  
  31  </xsl:stylesheet>

Here's the output from the formatted Ruby HTML code [twitxr.com]

Referemce: Syntax Manual [rubyforge.org]

A simple XSLT example

Produce a list of filenames using XML and XSLT

file: dir.xsl
   1  
   2  <?xml version="1.0"?>
   3  
   4  <xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
   5        
   6      <xsl:template match="dir">
   7      <div id="articles">
   8        <ul>
   9        <xsl:apply-templates select="records/file"/>
  10        </ul>
  11      </div>
  12      </xsl:template>
  13      
  14      <xsl:template match="records/file">
  15        <li><xsl:value-of select="."/></li>
  16      </xsl:template>
  17      
  18  </xsl:stylesheet>


file: dir.xml
   1  
   2  <dir>
   3    <summary>
   4      <directory>./</directory>
   5    </summary>
   6    <records>
   7      <file type='xml'>mjournal.xml</file>
   8      <file type='rb'>projxmlhelper.rb</file>
   9      <file type='rb'>feedpopulated.rb</file>
  10      <file type='rb'>squrl_handler.rb</file>
  11      <file type='cgi'>snurl.cgi</file>
  12      <file type='cgi'>dynalert.cgi</file>
  13      <file type='rb'>password_handler.rb</file>
  14      <file type='rb'>category.rb</file>
  15      <file type='rb'>gwd.rb</file>
  16      <file type='cgi'>new-journal-entry.cgi</file>
  17    </records>
  18  </dir>


then transforming the XML with the command 'xsltproc dir.xsl dir.xml' produces the following:
output:
   1  
   2  <div id='articles'>
   3    <ul>
   4      <li>mjournal.xml</li>
   5      <li>projxmlhelper.rb</li>
   6      <li>feedpopulated.rb</li>
   7      <li>squrl_handler.rb</li>
   8      <li>snurl.cgi</li>
   9      <li>dynalert.cgi</li>
  10      <li>password_handler.rb</li>
  11      <li>category.rb</li>
  12      <li>gwd.rb</li>
  13      <li>new-journal-entry.cgi</li>
  14    </ul>
  15  </div>

Save a Ruby source text file to XML.

This code will output a text file as an XML file which can later be transformed into an HTML file using a back-end XSLT processor called Gorg.

   1  
   2  #!/usr/bin/ruby 
   3  
   4  #file: rubytxt2xml.rb
   5  
   6  require 'rexml/document'
   7  include REXML
   8  
   9  class RubyTxt2XML
  10    
  11    def rubytxt2xml(h)
  12      h[:infilepath] = './' if h[:infilepath].nil?
  13      h[:outfilepath] = './' if h[:outfilepath].nil?
  14      h[:xmlfile] = h[:sourcefile][/^(.*)\.\w+$/,1] + '.xml' if h[:xmlfile].nil?
  15      buffer = File.new(h[:infilepath] + h[:sourcefile],'r').read
  16      
  17      doc = Document.new
  18      doc.add_element('ruby_txt')
  19      body = Element.new('source')
  20      body.text = CData.new(buffer)
  21      doc.root.add_element(body)
  22      
  23      file = File.new(h[:outfilepath] + h[:xmlfile],'w')
  24      file.puts doc
  25      file.close
  26      
  27    end
  28  end
  29  
  30  if __FILE__ == $0
  31    rt2x = RubyTxt2XML.new
  32    rt2x.rubytxt2xml(:sourcefile  => 'rubytxt2xml.rb')
  33  end

output:
   1  
   2  <ruby_txt>
   3    <source>
   4      <![CDATA[
   5        #!/usr/bin/ruby 
   6  
   7        #file: rubytxt2xml.rb
   8  
   9        require 'rexml/document'
  10        include REXML
  11  
  12        class RubyTxt2XML
  13          
  14          def rubytxt2xml(h)
  15            h[:infilepath] = './' if h[:infilepath].nil?
  16            h[:outfilepath] = './' if h[:outfilepath].nil?
  17            h[:xmlfile] = h[:sourcefile][/^(.*)\.\w+$/,1] + '.xml' if h[:xmlfile].nil?
  18            buffer = File.new(h[:infilepath] + h[:sourcefile],'r').read
  19            
  20            doc = Document.new
  21            doc.add_element('ruby_txt')
  22            body = Element.new('source')
  23            body.text = CData.new(buffer)
  24            doc.root.add_element(body)
  25            
  26            file = File.new(h[:outfilepath] + h[:xmlfile],'w')
  27            file.puts doc
  28            file.close
  29            
  30          end
  31        end
  32  
  33        if __FILE__ == $0
  34          rt2x = RubyTxt2XML.new
  35          rt2x.rubytxt2xml(:sourcefile  => 'rubytxt2xml.rb')
  36        end
  37      ]]>
  38    </source>
  39  </ruby_txt>

Position : fixed in MSIE6


   1  
   2  <?xml version="1.0" encoding="UTF-8"?>
   3  <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
   4  	"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
   5  
   6  <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="fr">
   7  <head>
   8  	<title>"position: fixed" compatible Microsoft Internet Explorer 6</title>
   9  	
  10  	
  11  	<!-- Code CSS for Firefox, Safari, Opera, Internet Explorer 7... -->
  12  	
  13  	<style type="text/css" media="screen">
  14  		
  15  	#fixed {
  16  		position: fixed;
  17  		left: 0; top: 0; right: 0;
  18  		width: 100%;
  19  		padding: 10px; background: gray;
  20  	}
  21  	
  22  	</style>
  23  	
  24  	
  25  	<!-- Code CSS for Internet Explorer 6 -->
  26  	
  27  	<!--[if lte IE 6]>
  28  	<style type="text/css" media="screen">
  29  	
  30  	#fixed {
  31  		position: absolute;
  32  		top: expression((document.documentElement.scrollTop || document.body.scrollTop) + this.offsetHeight - this.offsetHeight);
  33  	}
  34  	
  35  	</style>
  36  	<![endif]-->
  37  	
  38  	
  39  </head>
  40  
  41  <body>
  42  	
  43  	<div id="fixed">DIV in position: fixed;</div>
  44  	
  45  	<p>Content...</p>
  46  	<p>Content...</p>
  47  	<p>Content...</p>
  48  	<p>Content...</p>
  49  	<p>Content...</p>
  50  	<p>Content...</p>
  51  	<p>Content...</p>
  52  	<p>Content...</p>
  53  	<p>Content...</p>
  54  	<p>Content...</p>
  55  	<p>Content...</p>
  56  	<p>Content...</p>
  57  	
  58  </body>
  59  
  60  </html>


Source: Asselin Benoit Developpement, conception de sites internet

Convert from HTML to XHTML with HTML Tidy

This HTML Tidy example converts an html file into an xml file.

   1  
   2  tidy -asxhtml -numeric < index.html > index.xml


example found from Tip: Convert from HTML to XML with HTML Tidy [ibm.com]

Tidy with Ruby

Ruby interface to HTML Tidy Library Project (tidy.sf.net).

   1  
   2    require 'tidy'
   3    Tidy.path = '/usr/lib/libtidy.so'
   4    html = '<html><title>title</title>Body</html>'
   5    xml = Tidy.open(:show_warnings=>true) do |tidy|
   6      tidy.options.output_xml = true
   7      puts tidy.options.show_warnings
   8      xml = tidy.clean(html)
   9      puts tidy.errors
  10      puts tidy.diagnostics
  11      xml
  12    end
  13    puts xml


output
   1  
   2  true
   3  line 1 column 1 - Warning: missing <!DOCTYPE> declaration
   4  line 1 column 7 - Warning: plain text isn't allowed in <head> elements
   5  Info: Document content looks like XHTML 1.0 Transitional
   6  2 warnings, 0 errors were found!
   7  
   8  <html>
   9  <head>
  10  <meta name="generator"
  11  content="HTML Tidy for Linux/x86 (vers 1 September 2005), see www.w3.org" />
  12  <title>title</title>
  13  </head>
  14  <body>Body</body>
  15  </html>
  16  


Note: Couldn't get it to run on Ubuntu version 7.10 or 7.04 (LoadError: no such file to load -- tidy
), however it ran fine on Gentoo.

reference: http://tidy.rubyforge.org/

*update 18-Mar-08 16:15*
I got it working on Ubuntu I simply needed to add - require 'rubygems'

Make a variable CSS

Page.html
   1  
   2  <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
   3  	"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
   4  
   5  <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="fr" lang="fr">
   6  <head>
   7  	<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
   8  	
   9  	<title>Variable CSS</title>
  10  	<link rel="stylesheet" type="text/css" href="style.php" />
  11  </head>
  12  
  13  <body>
  14  
  15  
  16  <h1>Title</h1>
  17  
  18  <p class="color-1"> Text  Text  Text  </p>
  19  
  20  <p class="color-2"> Text  Text  Text  </p>
  21  
  22  <p class="color-3"> Text  Text  Text  </p>
  23  
  24  
  25  </body>
  26  
  27  </html>


Style.php
   1  
   2  <?php
   3  header('Content-Type: text/css');
   4  
   5  $color_0 = '#000000';
   6  $color_1 = '#ff0000';
   7  $color_2 = '#ff3300';
   8  $color_3 = '#ff6600';
   9  
  10  ?>
  11  
  12  * { font-family: sans-serif; }
  13  
  14  h1 {
  15  	padding: 5px;
  16  	color: <?= $color_0 ?>;
  17  	border: 5px solid <?= $color_2 ?>;
  18  	background-color: <?= $color_3 ?>;
  19  }
  20  
  21  p.color-1 { color: <?= $color_1 ?>; }
  22  p.color-2 { color: <?= $color_2 ?>; font-weight: bold; }
  23  p.color-3 { color: <?= $color_3 ?>; font-style: italic; }



Source: Asselin Benoit Développement, création de site internet amiens

Encode simple passwords

This code was used to demonstrate how to translate easy to remember simple (weak) passwords into more difficult to guess (strong) passwords. Example: Using Gmail I like an easy to remember password, I submit the password 'jr123' to the password_lookup.html page and what's returned to me is a stronger password 'NCC2SI1T'.

file: passwd_lookup.rb (generates an xml file containing an alphanumeric index with corresponding cryptic values)
   1  
   2  class PasswordLookup
   3  
   4    def initialize()
   5      chars =  (0..9).to_a  + Array.new(7) + ('A'..'Z').to_a + Array.new(6) + ('a'..'z').to_a 
   6      @chars = (0..9).to_a  + ('A'..'Z').to_a + ('a'..'z').to_a 
   7      @doc = Document.new()
   8      root = Element.new('codes')
   9      @doc.add_element(root)
  10  
  11      chars.each do |char|
  12        node = Element.new('code')
  13        if not char.nil? 
  14          node.attributes['index'] = char
  15          node.attributes['value'] = get_random_chars(2)
  16        end
  17        root.add_element(node)
  18      end
  19      puts root
  20    end
  21  
  22    
  23    def save(filepath)
  24      file = File.new(filepath,'w')
  25      file.puts @doc
  26      file.close
  27    end
  28          
  29    def get_random_chars(vword_size)
  30      newpass = Array.new(rand(vword_size) + 1, '').collect{@chars[rand(@chars.size)]}.join
  31      # return the encryption providing it doesn't already exist in the lookup table.
  32      if not /value=\'#{newpass}\'/.match @doc.root.elements.to_a.to_s 
  33       return newpass 
  34      else
  35       return get_random_chars(vword_size) 
  36      end
  37  
  38    end
  39    
  40    private :get_random_chars
  41    
  42  end


output extract: (codes - see also http://rorbuilder.info/pl/codes)
   1  
   2  <codes>
   3  <code value='4h' index='a'/><code value='B' index='b'/><code value='m' index='c'/>
   4  <code value='qf' index='d'/>
   5  </codes>


file: password_lookup.js
   1  
   2  var t;
   3  var m_doc;
   4  
   5  function loadXml() {
   6    url = 'http://rorbuilder.info/pl/codes';
   7    m_doc = XML.load(url);
   8  }
   9  
  10  function getCode(val,i) {
  11    pos = val.charCodeAt(i) - 48;
  12    node = m_doc.documentElement.childNodes[pos]
  13    return node.getAttribute('value');
  14  }
  15  
  16  function timed_update(keyCode,  val) {
  17    if (val.length > 0 && ((keyCode > 40) || (keyCode == 8)) ) {
  18      clearTimeout(t);
  19      t = setTimeout("revealCode('" + val + "')", 1000);
  20    }
  21    else
  22    {  
  23      o = document.getElementById('out1');
  24      if (val.length <= 0 && o.value.length > 0) {
  25        o.value = '';
  26      }
  27    }
  28    
  29  }
  30  
  31  function revealCode(val) {
  32    var iEnd = val.length;
  33    var newcode = '';
  34    for (i=0;i<iEnd;i++) {
  35        
  36      var codex = getCode(val,i);
  37      newcode += codex;
  38    }
  39    update(newcode);
  40  }
  41  
  42  function update(val){
  43    o = document.getElementById('out1');
  44    o.value = val;
  45    /*var o_copied = document.getElementById('out1').createTextRange();
  46    o_copied.exeCommand("Copy");*/
  47  }


file: password_lookup.html
   1  
   2    <body onload="loadXml()">
   3      <h1>Password lookup</h1>
   4      <dl>
   5      <dt><label for="in1">Enter password:</label></dt>    
   6      <dd><input type="text" name="in1" id="in1" value="" 
   7    onkeyup="timed_update(event.keyCode, this.value)" /></dd>
   8      
   9      <dt><label for="out1">Generated password</label></dt>
  10      <dd><input type="text" name="out1" id="out1" value=""/></dd>
  11      <dd><input type="button" name="clear1" id="clear1" onclick="clearPassword()" value="clear"/></dd>
  12  
  13      </dl>
  14      <p>see also: <a href="codes.xml" title="password code lookup table">codes.xml</a></p>
  15    </body>


Try out the encode a simple password demo [rorbuilder.info].

see also: Reading an XML file usng JavaScript [snippets.dzone.com]

Reading an XML file using JavaScript

Reads an xml file using JavaScript from a web page. Files used: loadxml.js (main script), readxml.js (client script), and readxml.html. The code for loadxml.js was copied from the article JavaScript and XML [devarticles.com]

file: loadxml.js
   1  
   2    XML.load = function(url) {
   3      var xmldoc = XML.newDocument();
   4      xmldoc.async = false;  
   5      xmldoc.load(url);
   6      return xmldoc;  
   7    };
   8  
   9  
  10  XML.newDocument = function(rootTagName, namespaceURL) {
  11      if (!rootTagName) rootTagName = "";
  12      if (!namespaceURL) namespaceURL = "";
  13  
  14      if (document.implementation && document.implementation.createDocument) {
  15          // This is the W3C standard way to do it
  16          return document.implementation.createDocument(namespaceURL, 
  17                         rootTagName, null);
  18      }
  19      else { // This is the IE way to do it
  20          // Create an empty document as an ActiveX object
  21          // If there is no root element, this is all we have to do
  22          var doc = new ActiveXObject("MSXML2.DOMDocument");
  23  
  24          // If there is a root tag, initialize the document
  25          if (rootTagName) {
  26              // Look for a namespace prefix
  27              var prefix = "";
  28              var tagname = rootTagName;
  29              var p = rootTagName.indexOf(':');
  30              if (p != -1) {
  31                  prefix = rootTagName.substring(0, p);
  32                  tagname = rootTagName.substring(p+1);
  33              }
  34  
  35              // If we have a namespace, we must have a namespace prefix
  36              // If we don't have a namespace, we discard any prefix
  37              if (namespaceURL) {
  38                  if (!prefix) prefix = "a0"; // What Firefox uses
  39              }
  40              else prefix = "";
  41  
  42              // Create the root element (with optional namespace) as a
  43              // string of text
  44              var text = "<" + (prefix?(prefix+":"):"") + tagname +
  45                  (namespaceURL
  46                   ?(" xmlns:" + prefix + '="' + namespaceURL +'"')
  47                   :"") +
  48                  "/>";
  49              // And parse that text into the empty document
  50              doc.loadXML(text);
  51          }
  52          return doc;
  53      }
  54  }; 


file: readxml.js
   1  
   2  function readXmlFile() {
   3    url = 'http://rorbuilder.info/pl/test123';
   4  
   5    doc = XML.load(url);
   6    alert(doc.documentElement.firstChild.nextSibling.firstChild.nodeValue);
   7  }


file: readxml.html
   1  
   2  <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
   3    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
   4  <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
   5    <head>
   6      <title>Read an XML file</title>
   7      <meta http-equiv="Content-Type" content="text/html;charset=utf-8"/>
   8      <script type="text/javascript" src="js/loadxml.js"/>
   9      <script type="text/javascript" src="js/readxml.js"/>
  10    </head>
  11  
  12    <body>
  13      <h1>ReadXML</h1>
  14      <p>
  15         If all goes well you should see an alert box display the message 'testing 123'
  16     </p>
  17      <p>Press the 'go' button to read the xml file '<a href="test123">test123</a>' 
  18         from the web server. 
  19         <input type="button" onclick="readXmlFile()" value="go"/>
  20      </p>
  21  
  22      
  23    </body>
  24  </html>


Note: To avoid the cross-site security error message 'permission denied', store all the files on the same web server.

To test the above code try out the demo to read the xml file [rorbuilder.info].

Zebra stripes on rows using XSLT

Using XSL every 2nd row will contain the class named 'stripe'.
   1  
   2    <xsl:element name="li">
   3          <xsl:if test="(position() mod 2) != 1">
   4            <xsl:attribute name="class"><xsl:text>stripe</xsl:text></xsl:attribute>
   5  	</xsl:if>
   6    </xsl:element>
« Newer Snippets
Older Snippets »
Showing 21-30 of 179 total