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

About this user

James Robertson http://www.r0bertson.co.uk

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

Adding helpful error messages to your Ruby code

This Ruby code raises an error if the XPath query fails because the attribute being queried did not exist for the given element.

  def map_pattr(node, fieldx, valuex)
    begin
    parameter = node.root.elements["parameter[@field='#{fieldx}']"]
    parameter.add_attribute('value', valuex)
    parameter
    
    rescue
      puts 'feedpopulated.rb: map_attr() the field ' + fieldx + ' was not found in params.'
      raise
    end
  end

Notice that a raise statement is used to ensure that the system error message is raised and any further code execution is halted.

Without adding a customized helpful message I would be left scratching my head trying to work out what the following system error message meant.
./feedpopulated.rb:27:in `map_pattr': undefined method `add_attribute' for nil:NilClass (NoMethodError)
     from ./feedpopulated.rb:51:in `create_record'
     from ./feedpopulated.rb:49:in `each'
     from ./feedpopulated.rb:49:in `create_record'
     from ./recordx.rb:91:in `call_create'
     from ./s3fileuploader_handler.rb:14:in `call'
     from ./s3fileuploader_handler.rb:40:in `invoke'
     from ./uploadtwitteraudio.rb:22:in `initialize'
     from /usr/lib/ruby/1.8/rexml/element.rb:890:in `each'
     from /usr/lib/ruby/1.8/rexml/xpath.rb:53:in `each'
     from /usr/lib/ruby/1.8/rexml/element.rb:890:in `each'
     from ./uploadtwitteraudio.rb:18:in `initialize'
     from ./uploadtwitteraudio.rb:72:in `new'
     from ./uploadtwitteraudio.rb:72


Reference: Programming Ruby: The Pragmatic Programmer's Guide - Exceptions, Catch, and Throw [ruby-doc.org]

Helpful XPath examples

A few XPath examples copied from XPath Syntax [w3schools.com]

Predicates
/bookstore/book[1] 	# Selects the first book element that is the child of the bookstore element. 
                        # Note: IE5 and later has implemented that [0] should be the first node, 
                        # but according to the W3C standard it should have been [1]!!
/bookstore/book[last()] 	# Selects the last book element that is the child of the bookstore element
/bookstore/book[last()-1] 	# Selects the last but one book element that is the child of the bookstore element
/bookstore/book[position()<3] 	# Selects the first two book elements that are children of the bookstore element
//title[@lang] 	# Selects all the title elements that have an attribute named lang

Selecting Unknown Nodes
/bookstore/* 	# Selects all the child nodes of the bookstore element
//* 	# Selects all elements in the document
//title[@*] 	# Selects all title elements which have any attribute

Selecting Several Paths
//book/title | //book/price  	# Selects all the title AND price elements of all book elements

Deleting a redundant shape message from the whiteboard queue

This code is used to remove a message from the whiteboard queue containing a shape which has recently moved it's position (x and y coordinates) on the board. Code extract from whiteboardqueue.rb

  def call_delete_shape(params)
    #get the shape's message id.
    doc = Document.new(params)
    shape_id = doc.root.elements["param[@var='id']"].text.to_s
    initialize_doc

    doc_xml = Document.new(decode2(@doc_file.root.to_s))
    id = doc_xml.root.elements["records/message/body/*[@id='#{shape_id}']"].parent.parent.attributes.get_attribute('id')
    delete_record(id)
    save_file
  end


*update 10:04pm*
Added the link to the project code http://github.com/jrobertson/whiteboardqueue/tree

Display a filtered list using XSLT

Following on from the post A simple XSLT example [dzone.com], this code lists all files which have the type 'rb' (equivalent to ls *.rb).

file: dir.xsl
<?xml version="1.0"?>

<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
      
    <xsl:template match="dir">
    <div id="articles">
      <ul>
      <xsl:apply-templates select="records/file[@type='rb']"/>
      </ul>
    </div>
    </xsl:template>
    
    <xsl:template match="records/file[@type='rb']">
      <li><xsl:value-of select="."/></li>
    </xsl:template>
    
</xsl:stylesheet>

output:
<div id='articles'>
  <ul>
    <li>projxmlhelper.rb</li>
    <li>feedpopulated.rb</li>
    <li>squrl_handler.rb</li>
    <li>password_handler.rb</li>
    <li>category.rb</li>
    <li>gwd.rb</li>
  </ul>
</div>



*update 11:58am 26-Feb*
Here's a filter I will be using in my projects

<?xml version="1.0"?>

<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
      
    <xsl:template match="dir">
    <div id="articles">
      <ul>
      <xsl:apply-templates select="records/file"/>
      </ul>
    </div>
    </xsl:template>
    
    <xsl:template match="records/file">
      <xsl:if test="@type=$type">
        <li><xsl:value-of select="."/></li>
      </xsl:if>
    </xsl:template>
    
</xsl:stylesheet>

Using XPath in JavaScript (Mozilla based)

The following JavaScript code uses XPath to select a specific element. Note: This code works for Firefox, but Internet Explorer has it's own implementation of XPath. see Introduction to using XPath in JavaScript [mozilla.org]

doc (xml document)
<codes>
  <codex value='bQ' index='Q'/>
  <codex value='S' index='R'/>
  <codex value='PU' index='S'/>
  <codex value='ji' index='T'/>
  <codex value='0' index='U'/>
  <codex value='33' index='V'/>
  <codex value='A' index='W'/>
  <codex value='tO' index='X'/>
  <codex value='fW' index='Y'/>
  <codex value='P' index='Z'/>
  <codex value='4h' index='a'/>
  <codex value='B' index='b'/>
  <codex value='m' index='c'/>
  <codex value='qf' index='d'/>
  <codex value='uJ' index='e'/>
</codes>


Assuming the doc object below contains the XML data from above.
var nodesSnapshot = doc.evaluate("codes/codex[@index='a']", doc, null, XPathResult.
  UNORDERED_NODE_SNAPSHOT_TYPE, null );
node = nodesSnapshot.snapshotItem(0);
msg = "The secret code for '" + node.getAttribute('index') + "' is " + node.getAttribute('value');
alert(msg);


output (value from the alert box)
"The secret code for 'a' is 4h"


see also: Reading an XML file using JavaScript
« Newer Snippets
Older Snippets »
Showing 1-5 of 5 total  RSS