Raaum’s Rails Reader

Rails 1 Comment »

Rails Documentation for the Working Developer

http://rails.raaum.org/

Installing Ruby and rails on Ubuntu Feisty

Rails, Ruby 1 Comment »

The image “http://www.rubyonrails.org/images/rails.png” cannot be displayed, because it contains errors.

Found these instructions at http://www.aptana.com/forums/viewtopic.php?p=10640

Blogging to ensure I have a copy, credits go to janmartin.

Lets start with a fresh Ubuntu Feisty Fawn 7.04 installation:

  • sudo apt-get install build-essential
  • sudo apt-get install sun-java6-jdk
  • sudo update-java-alternatives –list
  • sudo apt-get install ruby irb ri rake rdoc ruby1.8-dev rubygems
  • sudo apt-get install libmysql-ruby mysql-server
  • sudo gem update –system
  • sudo gem install rails –include-dependencies

Some tests:

  • ruby –version
  • rails –version
  • mysql –version
  • gem list

END of command line installation

Download
Aptana + Rails (Linux).
Extract it into ~/aptana

Follow these instructions:
# Open up Aptana, and Navigate to the Help > Software Updates > Find and Install menu.
# Select “Search for new features to install”, click “Finish”
# Select “Ruby on Rails Development Environment”, click “Finish”
# Select the Ruby on Rails Development Environment feature.
# Continue through the dialog boxes until complete.

Follow these instructions:
http://www.aptana.com/forums/viewtopic.php?t=1397

Configure:
Menu -> Window -> Preferences

Rails -> Configuration
Rails path: /usr/bin/rails
Rake path: /usr/bin/rake

Ruby
Installed interpreters:
/usr

Ri/rdoc
RDoc path:/usr/bin/rdoc
Ri path: /usr/bin/ri

Finished!

Powered by ScribeFire.

Ruby Class Cheat sheet

Ruby 1 Comment »

The following is my ruby class cheat sheet, aimed at developers new to ruby and rails. 

class MyClass                   #class declaration, notice the capital letter as this is a Constant
    attr_reader :readOnlyProperty, …        #shortcut to save writing a property getter
    attr_writer :writeOnlyProperty, …       #shortcut to save writing a property setter
    attr_accessor :readWriteProperty, …     #shortcut to save writing a property setter and getter

    def initialize              #class initialization method
        @instanceVar=1          #instance variable, available throughout an instance of the class.
        @readOnlyProperty=2    
        @writeOnlyProperty=3
        @readWriteProperty=4
    end

    def instanceVar             #property getter
        @instanceVar            #return the value of the instance variable
    end

    def instanceVar=(value)     #property setter
        @instanceVar = value    # set the instance variable to the passed in value
    end

    def instanceMethod          #instance method, available to all instances, this is the instance
    end

    def MyClass.classMethod     #class method, only accessible via the class, this is the class
    end

    CLASSCONSTANT = ["a","b","c"] #constant defined by the class accessible by all instances note its in uppercase

end

I hope you have found this useful.  If you have anything to add please comment.

Going loopy with JavaScript

JavaScript 2 Comments »

I am in the middle of writing a JavaScript tree that can handle 100s of thousands of nodes in the tree and needed to see if I can optimize the code.  Trying to optimize the loop iterations for array objects, I put together a test case to time the efficiency of various different types of loops in JavaScript.

The test

Create an array of 1 million numbers 0 to 1 million, for each of the loop tests, increment a counter then display it at the end of the iterations.

The test covers the following loops:

  1. ForLoop - standard for loop accessing the length of the array in the iterator
  2. ForLoopLocalCount - standard for loop, accessing the length of the array stored in a local variable before the iterator
  3. ForLoopLocalCountAndIterator - standard for loop accessing the count and the iterator from local variables
  4. ForInLoop - standard For In loop
  5. ForInLoopLocalItem - standard For In Loop, but declaring the iterator variable locally first.
  6. WhileLoop - While loop iterator accessing the length at each iteration
  7. WhileLoopCountFirst - while loop but storing the length of the array in a local variable before the iterator.

 

var loopTest = {
    itemCount : 1000000,
    items : [],
    
    initArray : function()
    {
        for(var x=0; x < this.itemCount; x++)
        {
            this.items.push(x);
        }
        console.log(this.items.length);
    },
    
    forLoop : function()
    {
        var total=0;
        for(var i=0;i < this.items.length; i++)
        {
            total ++;
        }
        console.log(total );
    },
    
    forLoopLocalCount : function()
    {
        var total=0;
        var count = this.items.length;
        for(var i=0;i < count; i++)
        {
            total ++;
        }
        console.log(total );
    },
    
    forLoopLocalCountAndIterator : function()
    {
        var total=0;
        var count = this.items.length;
        var i = 0;
        for(i=0;i < count; i++)
        {
            total ++;
        }
        console.log(total );
    },
    
    forInLoop : function()
    {
        var total=0;
        for(item in this.items)
        {
            total ++;
        }
        console.log(total);
    },
    
    forInLoopLocalItem : function()
    {
        var total=0;
        var item = null;
        for(item in this.items)
        {
            total ++;
        }
        console.log(total);
    },
    
    whileLoop : function()
    {
        var total=0;
        var i = 0;
        while(i<this.items.length)
        {
            total ++;
            i++;
        }
        console.log(total );
    },
    
    whileLoopCountFirst : function()
    {
        var total=0;
        var i = 0;
        var count = this.items.length;
        while(i<count)
        {
            total ++;
            i++;
        }
        console.log(total );
    },
    
    runTests : function()
    {
        this.initArray();
        this.forLoop();
        this.forLoopLocalCount();
        this.forLoopLocalCountAndIterator();
        this.forInLoop();
        this.forInLoopLocalItem();
        this.whileLoop();
        this.whileLoopCountFirst();
        console.log("Complete.");
    }
}

 

The test was profiled using the firebug profile option and run in Firefox 2.0.0.4 on a Dual Core Pentium 3.2Ghz machine with 3Gb of ram.

 

Results & Conclusion

The test results are shown in the table to the right. So what can we conclude from the results?

  • Don’t use a For In loop.  There is a small increase in performance if you allocate the item variable outside of the loop, but it is still up to 31 times slower than using a for or while loop.
  • Always ensure that the count (used in the loop exit test) is stored in a temporary variable outside of the iterator i.e. rather than calling array.length in the iterator exit test.
  • When local variables are used to store the iterator and count, a for loop performs the same as a while loop.  One would assume that the JavaScript.
  • In a For loop, declaring the iterator variable outside of the loop actually slows the iteration down! This I did not expect.

Firebug - Console options

JavaScript 1 Comment »

Firebug, the ultimate javascript debugger for firefox, automatically creates a “console” object that has various methods that can be used to aid in debugging your javascript apps.

Full Documentation is here http://www.getfirebug.com/console.html

console.log() is the most used, with the ability to pass parameters and a formatted string.

One of the nice things is, if you log an object it displays all the objects properties as well.

For performance testing console.time(id) and console.timeEnd(id) are very useful.

consolt.trace() will even dump the full stack at the point it is called.

 

If you haven’t got firebug, it’s a must if you are developing with firefox.  Go get it here

101 of Memory Leak causes in JavaScript

JavaScript 1 Comment »

Really nice article explaining some of the gotcha’s that can cause memory leaks in JavaScript

http://www-128.ibm.com/developerworks/web/library/wa-memleak/

Ext.Format extension for thousands separator formatting

Ext General, JavaScript No Comments »

A simple function, the basis of was in the public domain (see comments) to format a number with thousand separators.

 

Ext.apply(Ext.util.Format,{
 
    decimalSeparator : '.',
    thousandSeparator : ',',
        
    /* Adapted from http://www.mredkj.com/javascript/nfbasic.html, 
     * Public Domain, without copyright, and can be used without restriction: 
     * see http://www.mredkj.com/legal.html
     */    
    asThousands : function(value)
    {
        value = parseInt(value,10) + '';
        var x = value.split(this.decimalSeparator);
        var x1 = x[0];
        var x2 = x.length > 1 ? this.decimalSeparator + x[1] : '';
        var rgx = /(\d+)(\d{3})/;
        while (rgx.test(x1)) {
            x1 = x1.replace(rgx, '$1' + this.thousandSeparator + '$2');
        }
        return x1 + x2;
    }
});

Ext.util.SpriteManager

Ext Components, JavaScript 3 Comments »

One of the ways of improving web page performance (especially in RIA - Rich Internet Applications) where there are lots of small images that need to be displayed, e.g. on a toolbar, is to create a compound image and then use css to select a section of the image to display.  In the javascript world this is known as using sprites.  In the world of C#/vb/Delphi this is well known and there have always been ImageList components that store images in this form.

So instead of creating single images :    we create a composite image e.g. (have added a second row as well)

To make the process of assigning the correct css style to select on of the images to display, I have created a SpriteManager addition to Ext JS as follows:

 

 
Ext.namespace('Ext', 'Ext.util');
 
Ext.util.SpriteManager = function(config){
        Ext.apply(this,config,{
                spriteSource:true,
                spriteWidth:1,
                spriteHeight:1,
                spriteColumns:1,
                spriteRows:1
                });
};
 
 
Ext.util.SpriteManager.prototype = {
 
    /**
     * Gets the CSS Style for the appropriate image
     * @param {Object...} spriteLocation Expects an object with an X and Y location of the sprite to display
     * @return {String} returns the CSS style string enclosed in braces {}
     */
    getSpriteCSS : function(spriteLocation){
            var locationX = spriteLocation.x-1 || 0;
            var locationY = spriteLocation.y-1 || 0;
            var spriteCss = ['{'];
            var spriteW = this.spriteWidth / this.spriteColumns;
            var spriteH = this.spriteHeight / this.spriteRows;
            var spriteXPos = locationX * spriteW;
            var spriteYPos = locationY * spriteH;
                         
            if(!typeof this.spriteSource =="boolean")
            {            
                spriteCss.push('background:url(' + this.spriteSource +');');
            }
            spriteCss.push('height:' + spriteH + 'px;');
            spriteCss.push('width:' + spriteW + 'px;');
            spriteCss.push('background-position:-' + spriteXPos + 'px -' + spriteYPos + 'px;');
            spriteCss.push('}');
            return spriteCss.join("");
    },
        
    /**
     * Applies the CSS Style for the appropriate sprite image to an element
     * @param {element} Ext.Element to apply the sprite style to.
     * @param {Object...} spriteLocation Expects an object with an X and Y location of the sprite to display
     */
        applySpriteCss : function(el, spriteLocation)
        {
            var css = this.getSpriteCSS(spriteLocation);
            el.applyStyles(css);
        }
};

Here is an example of the usage:

<script type="text/javascript">
var spriteManager = new Ext.util.SpriteManager({
            spriteSource:"sprites.png",
            spriteWidth:64,
            spriteHeight:34,
            spriteColumns:4,
            spriteRows:2
            });
</script>
 
...
 
<img id="test" src="images/default/s.gif" /> 
<a href="javascript:spriteManager.applySpriteCss(Ext.get('test'),{x:1,y:1});">Image 1,1</a>
<a href="javascript:spriteManager.applySpriteCss(Ext.get('test'),{x:2,y:1});">Image 2,1</a>
<a href="javascript:spriteManager.applySpriteCss(Ext.get('test'),{x:1,y:2});">Image 1,2</a>
<a href="javascript:spriteManager.applySpriteCss(Ext.get('test'),{x:2,y:2});">Image 2,2</a>

  ** Updated 2/5/2007 - spriteSource does not now need to be supplied if the element already has a css style specifying the background image.

Non-record based Json calls across Domains with Ext

Ext General 1 Comment »

From a forum question I posted at Ext: http://extjs.com/forum/showthread.php?t=5430

I am trying to make a call to a webpage that returns a json object that is hierarchical in nature and not record based so as far as I am aware, jsonreader / datareader are not suitable.

The Server returns something looking like this:

   1: (
   2:     { 
   3:     children: [
   4:         { 
   5:         id : "1", 
   6:         name : "Dim Item 1", 
   7:         children : [
   8:             { 
   9:             id : "1.0", 
  10:             name : "Dim Item 1.0"
  11:             },
  12:             { 
  13:             id : "1.1", 
  14:             name : "Dim Item 1.1"
  15:             } 
  16:         ]
  17:         } 
  18:     ]
  19:     }
  20: );

Where each item can have children in a hierarchy. (I am not trying to use this data with the Ext Tree by the way)

To complicate matters the server providing the data is hosted on a different port, so I have to use the Ext.data.ScriptTagProxy to get the data, which is successful. I had a few teething problems until I realized you had to wrap the json object returned with the callback function name.
However, with my limited understanding and debugging the code, the Ext.data.ScriptTagProxy requires a reader to be supplied, but all I want in this instance is the object.

This is the client side code:

   1: function GetData()
   2: {
   3:         var url = "http://localhost:4855/largeJasonHierarchy.aspx";
   4:         var conn = new Ext.data.ScriptTagProxy({
   5:             url: url
   6:         });
   7:         
   8:         var reader = new Ext.data.ObjectReader();
   9:         conn.load({},reader,GotData);
  10: }
  11:  
  12:  
  13:  
  14: function GotData(x)
  15: {
  16:     alert(x);
  17: }

As a reader is required, I had to hack a copy of the jsonReader to create a ObjectReader that simply returns the object and does not process it.

ObjectReader.js

   1: Ext.data.ObjectReader = function(meta, recordType){
   2:     Ext.data.ObjectReader.superclass.constructor.call(this, meta, recordType);
   3: };