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-10 of 31 total  RSS 

Convert REXML document records into a Hash

This script make it easier to extract the information from an XML document into a hash. The XML file used in this example uses the ProjectX format.

- Retrieve a single record -
   1  h1 = doc.record('records/caller')

=> {"name"=>"Parents at the Doorphone", "caller_id"=>"doorphone2", "audio_file"=>"parents-doorphone.ogg"}

- Retrieve many records
   1  h1 = doc.records('records/caller')

=> [{"name"=>"parents", "caller_id"=>"54768002343", "audio_file"=>"parents.ogg"}, {"name"=>"unknown", "caller_id"=>"", "audio_file"=>"unknown_caller.ogg"}, {"name"=>"Doorphone", "caller_id"=>"Doorphone", "audio_file"=>"someone-doorphone.ogg"}, {"name"=>"Anonymous", "caller_id"=>"Anonymous", "audio_file"=>"anonymous_caller.ogg"}, {"name"=>"E61", "caller_id"=>"21384757396", "audio_file"=>"my-e61-caller.ogg"}, {"name"=>"6600", "caller_id"=>"87662383483", "audio_file"=>"my-6600-caller.ogg"}, {"name"=>"Doorphone", "caller_id"=>"doorphone", "audio_file"=>"someone-doorphone.ogg"}, {"name"=>"Parents at the Doorphone", "caller_id"=>"doorphone2", "audio_file"=>"parents-doorphone.ogg"}]


Here's the code which extends the REXML class and the Array class
   1  
   2  # convert an array into a hash
   3  class Array
   4    def to_h
   5      Hash[*self]
   6    end
   7  end
   8  
   9  class REXML::Document
  10  
  11    def record(xpath)
  12      self.root.elements.each(xpath + '/*'){}.inject([]) do |r,node|
  13        r << node.name.to_s << node.text.to_s
  14      end.to_h
  15    end
  16  
  17    def records(xpath)
  18      self.root.elements.each(xpath){}.map do |row|
  19        row.elements.each{}.inject([]) do |r,node|
  20          r << node.name.to_s << node.text.to_s
  21        end.to_h
  22      end
  23    end
  24  
  25  end

Creating a class with JS.class

Source: JS.Class - Ruby-style JavaScript [jcoglan.com]
   1  
   2  var Animal = new JS.Class({
   3    initialize: function(name) {
   4      this.name = name;
   5    },
   6  
   7    speak: function(things) {
   8      return 'My name is ' + this.name + ' and I like ' + things;
   9    }
  10  });

   1  
   2  var nemo = new Animal('Nemo');    // nemo.name == "Nemo" 
   3  
   4  nemo.speak('swimming')
   5  // -> "My name is Nemo and I like swimming"

Making methods immutable in Ruby

Source: scie.nti.st ยป Making methods immutable in Ruby (or, Death to Monkey Patching) [scie.nti.st]

   1  
   2  require 'rubygems'
   3  require 'immutable'
   4  
   5  module Foo
   6    include Immutable
   7  
   8    def foo
   9      :foo
  10    end
  11  
  12    immutable_method :foo
  13  end
  14  
  15  # Now re-open Foo and redefine foo()
  16  module Foo
  17    def foo
  18      :baz
  19    end
  20  end
  21  
  22  include Foo
  23  
  24  foo # => :foo.

Shorten REXML's XPATH statement

   1  class REXML::Document
   2    def [](xpath)
   3      if (xpath.to_s.match(/[^0-9]/)) and xpath.to_i != -1 then
   4        self.root.elements[xpath] 
   5      else
   6        super
   7      end
   8    end
   9  end
  10  
  11  
  12  doc = Document.new("<div><p>123</p><p>456</p></div>")
  13  
  14  #Instead of typing 
  15  doc.root.elements['p[last()]'].text
  16  => 456
  17  
  18  # we can now type
  19  doc['p[last()]'].text
  20  => 456

Convert a string to a REXML document

   1  
   2  require 'rexml/document'
   3  include REXML
   4  
   5  class String
   6    def to_doc()
   7      Document.new(self)
   8    end
   9  end
  10  
  11  
  12  doc2 = "<div><p>123</p><p>456</p></div>".to_doc
  13  puts doc2.root.elements['p[last()]'].text

=> 456

How to call a base class method

This Ruby example demonstrates using the keyword super to call the superclass method.

   1  
   2  class Claw
   3    def grab(item)
   4      puts item + ' grabbed'
   5    end
   6  end
   7  
   8  class Hand < Claw
   9    def grab(item)
  10      super(item)
  11    end
  12  end
  13  
  14  h = Hand.new
  15  h.grab('apple')

output
   1  
   2  apple grabbed

for more information: http://www.google.com/search?q=ruby+keyword+super

before? and after? - Ruby Time class mixin

The mixin below allows comparison between two Time objects using the more intuitive and natural-sounding before? and after? methods.

Some examples (using Rails' ActiveSupport Time extensions or (preferred) the 'units' gem):

   1  2.minutes.ago.after? Time.now # => false


   1  Time.now.before? 2.hours.from_now # => true


   1  module BeforeAndAfter
   2  
   3    LEFT_SIDE_LATER  = 1
   4    RIGHT_SIDE_LATER = -1
   5    
   6    def before?(input_time)
   7      (self <=> input_time) == RIGHT_SIDE_LATER
   8    end
   9    
  10    def after?(input_time)
  11      (self <=> input_time) == LEFT_SIDE_LATER
  12    end
  13  end
  14  
  15  Time.send :include , BeforeAndAfter

Get all classes within a package

The code below gets all classes within a given package. Notice that it should only work for classes found locally, getting really ALL classes is impossible.

   1  
   2      /**
   3       * Scans all classes accessible from the context class loader which belong to the given package and subpackages.
   4       *
   5       * @param packageName The base package
   6       * @return The classes
   7       * @throws ClassNotFoundException
   8       * @throws IOException
   9       */
  10      private static Class[] getClasses(String packageName)
  11              throws ClassNotFoundException, IOException {
  12          ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
  13          assert classLoader != null;
  14          String path = packageName.replace('.', '/');
  15          Enumeration<URL> resources = classLoader.getResources(path);
  16          List<File> dirs = new ArrayList<File>();
  17          while (resources.hasMoreElements()) {
  18              URL resource = resources.nextElement();
  19              dirs.add(new File(resource.getFile()));
  20          }
  21          ArrayList<Class> classes = new ArrayList<Class>();
  22          for (File directory : dirs) {
  23              classes.addAll(findClasses(directory, packageName));
  24          }
  25          return classes.toArray(new Class[classes.size()]);
  26      }
  27  
  28      /**
  29       * Recursive method used to find all classes in a given directory and subdirs.
  30       *
  31       * @param directory   The base directory
  32       * @param packageName The package name for classes found inside the base directory
  33       * @return The classes
  34       * @throws ClassNotFoundException
  35       */
  36      private static List<Class> findClasses(File directory, String packageName) throws ClassNotFoundException {
  37          List<Class> classes = new ArrayList<Class>();
  38          if (!directory.exists()) {
  39              return classes;
  40          }
  41          File[] files = directory.listFiles();
  42          for (File file : files) {
  43              if (file.isDirectory()) {
  44                  assert !file.getName().contains(".");
  45                  classes.addAll(findClasses(file, packageName + "." + file.getName()));
  46              } else if (file.getName().endsWith(".class")) {
  47                  classes.add(Class.forName(packageName + '.' + file.getName().substring(0, file.getName().length() - 6)));
  48              }
  49          }
  50          return classes;
  51      }

Simple camera class in FTS - lookAt function.

// Camera class for FTS

   1  
   2  /// Makes the camera look at a certain point.
   3  /** This function makes the camera look at a certain point. If that point is the same as its
   4   *  current position, the camera moves back the (current) distance |camera-target|.
   5   *
   6   * \param in_vTgt The position where the camera should look at.
   7   *
   8   * \return If successfull: ERR_OK
   9   * \return If failed:      An error code < 0
  10   *
  11   * \author Pompei2
  12   */
  13  CFTSCamera *CFTSCamera::lookAt(const CFTSVector & in_vTgt)
  14  {
  15      // Calculate the new front vector that points to the target.
  16      CFTSVector vNewFront = (in_vTgt - m_vPos).normalize();
  17  
  18      // The two vectors are in one plane. This gives us the cosine of the angle between
  19      // these two vectors.
  20      float fDotProd = vNewFront.dot(m_vFront);
  21      if(fDotProd > 1.0f || fDotProd < -1.0f)
  22          return this;
  23  
  24      // By getting the arc cosine of this, we get the angle in radians between the two
  25      // vectors. But we only get an angle between 0 and pi, that will be a problem.
  26      float fAlpha = acosf(fDotProd);
  27  
  28      // Here we get the normal to these two vectors, we will need to rotate our front
  29      // vector around this normal.
  30      CFTSVector vNormal = vNewFront.cross(m_vFront).normalize();
  31  
  32      // As I said, we have a problem: as we only get an angle between 0 and pi,
  33      // we don't know if we need to rotate clockwise or counterclockwise ...
  34      // We solve this problem by just trying it out.
  35      CFTSVector vFrontTest = m_vFront.rotate(vNormal, fAlpha);
  36  
  37      // If the dot product is near to one, it means we were right. with our guess
  38      // rotating counterclockwise.
  39      // Else, we must rotate clockwise.
  40      fDotProd = vFrontTest.dot(vNewFront);
  41      if(fabs(fDotProd) > (1.0f - D_FTS_DELTA)) {
  42              m_vFront = vFrontTest;
  43              m_vUp = m_vUp.rotate(vNormal, fAlpha);
  44              m_vRight = m_vRight.rotate(vNormal, fAlpha);
  45      } else {
  46              m_vFront = m_vFront.rotate(vNormal, -fAlpha);
  47              m_vUp = m_vUp.rotate(vNormal, -fAlpha);
  48              m_vRight = m_vRight.rotate(vNormal, -fAlpha);
  49      }
  50  
  51      // If the dot product is near to -1, it means we look the wrong way.
  52      // To correct this, we just rotate pi radians (a half circle).
  53      if(fDotProd < -(1.0f - D_FTS_DELTA))
  54          this->rotateYRadians(M_PI);
  55  
  56      return this;
  57  }

Printing out the full path of a resource on the classpath

// displaying the full path of a resource found by the class loader on the classpath, here the log4j.xml file
   1  
   2  String resourceName = "/log4j.xml"; // pay attention to the leading '/' !
   3  URL location = AnyClass.class.getResource(resourceName);
   4  
   5  if (location != null) {
   6      System.out.println(location.getPath());
   7  } else {
   8      System.out.println(resourceName + " not found on the classpath");
   9  }
« Newer Snippets
Older Snippets »
Showing 1-10 of 31 total  RSS