Beginners Tutorial: Routing in Rails 2.0 (with REST) – Part 3 of n

Part 4

Part 3

At the end of part 2, routes.rb looked like this:

ActionController::Routing::Routes.draw do |map|
  map.connect 'music', :controller => "albums", :action => "index"
  map.connect '', :controller => "albums", :action => "index"
  map.connect 'music/show/:id', :controller => "albums", :action => "show"
  map.connect 'music/delete/:id', :controller => "albums", :action => "destroy"
  map.connect 'music/edit/:id', :controller => "albums", :action => "edit"
  map.connect 'music/update/:id', :controller => "albums", :action => "update"
  map.connect 'music/new', :controller => "albums", :action => "new"
  map.connect 'music/create', :controller => "albums", :action => "create"
end

To simplify things, let’s remove the routing rule for the empty URL. Remove line 3.

We can no longer browse to http://localhost:3000/, but we can still browse to http://localhost:3000/music. Besides that, the site should continue to work as before.
Looking at the routes.rb file we see 7 rules defined.

ActionController::Routing::Routes.draw do |map|
  map.connect 'music', :controller => "albums", :action => "index"
  map.connect 'music/show/:id', :controller => "albums", :action => "show"
  map.connect 'music/delete/:id', :controller => "albums", :action => "destroy"
  map.connect 'music/edit/:id', :controller => "albums", :action => "edit"
  map.connect 'music/update/:id', :controller => "albums", :action => "update"
  map.connect 'music/new', :controller => "albums", :action => "new"
  map.connect 'music/create', :controller => "albums", :action => "create"
end

We have 7 rules and only one database table. Does this mean we need to add 7 more rules for every table we add? No, there are ways to reduce the amount of explicitly defined rules.

When Rails receives a URL it tries to find a matching routing rule. It does this by comparing the URL to the pattern string in the rule.
The pattern string for map.connect ‘music/create’, :controller => “albums”, :action => “create” Is: music/create

The pattern string for map.connect ‘music/edit/:id’, :controller => “albums”, :action => “edit”
Is: music/edit/:id

The :id is a Ruby symbol and is referred to as a receptor. If you are new to Ruby you may not be too familiar with symbols. I once came across a short and sweet description of a symbol “A symbol is the name badge, not the person”. I may have read that in here.

A receptor is used as a wildcard. It matches anything that it is compared against. The wildcard receptor gets passed into the controller action within the params hash e.g.

def edit
    @album = Album.find(params[:id])
end

You can change :id to almost anything as long as you remember to change it in the controller and in the views where the URL is generated e.g. when using link_to. I recommend you use :id as that is the convention.

Continue reading

Very High Level Language – So what?

When I first heard about Python I thought this is just great. I have had to listen to countless conversations about Java vs. C# and now we have to go through it all again with Python thrown in. I know Python is older than Java, but I only came across it after C++, Java etc. Python and Ruby are described as being Very High Level Languages (VHLL). When I heard that term for the first time I thought here comes another meaningless, yet ubiquitously used acronym. At first I did not pay much attention to these languages. I was very familiar with Java, C# and PHP. I figured Ruby and Python could not be too different from these languages. And sure, I may have been caught up in some Microsoft sales propaganda…

As with many developers, it was Rails that pushed me into learning Ruby. From the start, I really enjoyed Ruby – and still do. Dynamic scripting is a real eye-opener! Although I was enjoying this new dynamic paradigm, I still did not see much value in calling it a Very High Level Language.

This all changed at SPA. I attended “Agile Development for the Web and Elsewhere: A Tutorial in Python” presented by Nick Efford. In my opinion, this was the best session at SPA. Well organised and the content was spot on. It was a 6 hour session and Nick made many valuable points. He also explained the VHLL concept in great way. This was done with the use of this simple and effective slide.

Mental-model

This is when I had my first real VHLL a-ha! moment. Nick had placed Python and Ruby in a different class to Java and C#! I had realised that these languages were dynamically typed while Java and C# are (mostly) statically typed. I knew I was not comparing apples with apples, but I thought I was comparing apples with oranges. It turns out that I was comparing apples with apple pie.

When coding in C# you do not need to worry about the low level details that a C programmer needs to be concerned about. Similarly, when programming in Ruby you should not be concerned about the low level details that a C# programmer needs to worry about. Most of us are aware of the low level details a C programmer is faced with e.g. garbage collection. Now what low level details are there at the C#java level? We can explore this with a simple example.

Continue reading

Ajax Fundamentals – Part 2

Index | Part 1 | Part 2 | Part 3 | Part 4 | Part 5

2. Ajax Communication

2.1. Handling the Server Response

The XMLHttpRequest object is used to receive the sever response. Two methods are used, namely responseText and responseXML. The responseText method returns text and the responseXML returns an object that can be parsed as a DOM object.

The responseText is limited however its functionality can be enriched when combining it with the innerHTML property. This is a simple method of including dynamic content within the page. The following code is a selected code extract from an example supplied by Foundations of Ajax.


function startRequest()
{
    createXMLHttpRequest();
    xmlHttp.onreadystatechange = handleStateChange;
    xmlHttp.open("GET", "innerHTML.xml", true);
    xmlHttp.send(null);
}
function handleStateChange()
{
    if(xmlHttp.readyState == 4)
    {
        if(xmlHttp.status == 200)
        {
            document.getElementById("results").innerHTML =                 xmlHttp.responseText;
        }
    }
}


  <body>
    <form action="#">
      <input type="button" value="Search for Today's Activities" onclick="startRequest();"/>
    </form>
<div id="results"></div>
</body>

The above example refers to “innerHTML.xml”. This is a document that contains HTML tags that define an HTML table. When handleStateChange executes, an HTML table is embedded between within ‘results’ div tags and a table will be displayed.The innerHTML property is not a standard therefore not all browsers offer the same support. Microsoft Internet Explorer restricts innerHTML property to read only on certain elements. Using the W3C DOM is the preferred method for manipulating the web page. In order to use the W3C DOM the script needs to extract specific data from the server’s response. Selecting data from XML is far simpler than finding the data in plain text. The script can use responseXML to receive a response in XML format.The responseXML method returns an XML object that meets the W3C DOM specification. This standard is supported by most modern browsers. Using the API provided by DOM, the script can traverse the XML document. The following code shows an example of this.


function showArtistAlbums(artist)
{
    var artistname = artist;
    var xmlDoc = req.responseXML;// req is an XMLHttpRequest object
    var node = xmlDoc.getElementsByTagName(artistname)[0];
    var albums = node.getElementsByTagName("album");
    var result = artistname;

    for(var i = 0; i < albums.length; i++)
    {
        result = result + "n * " + albums&#91;i&#93;.                         childNodes&#91;0&#93;.nodeValue;// Retrieves the text value
    }
}

&#91;/sourcecode&#93;

The objective of Ajax is to modify only relevant parts of a web page without refreshing the entire page.   This eases the load on the web server and provides a better user experience.   Performing these ‘precision updates' is possible by making use of the W3C DOM. <a href="http://www.amazon.com/Foundations-Ajax-Foundation-Ryan-Asleson/dp/1590595823/ref=pd_bbs_sr_1?ie=UTF8&amp;s=books&amp;qid=1207069447&amp;sr=8-1" target="_blank">Foundations of Ajax gives a good example of dynamically appending rows to an HTML table.   A Sample of the code is shown below.   Note that the tbody tag is used, in this case the tbody element has an ID equal to "resultsBody".



function addTableRow(address, price, comments)
{
    var row = document.createElement("tr");
       var cell = createCellWithText(address);
       row.appendChild(cell);
       cell = createCellWithText(price);
       row.appendChild(cell);
       cell = createCellWithText(comments);
       row.appendChild(cell);
       document.getElementById("resultsBody").appendChild(row);
}
function createCellWithText(text)
{
       var cell = document.createElement("td");
       var textNode = document.createTextNode(text);
       cell.appendChild(textNode);
       return cell;
}

Continue reading

Ajax Fundamentals – Part 1

Index | Part 1 | Part 2 | Part 3 | Part 4 | Part 5

1. Introduction to Ajax

On the 18’th of February 2005 Jesse James Garret introduced the term Ajax in an article called “Ajax: A New Approach to Web Applications“. That article explained that Ajax is an acronym for Asynchronous JavaScript and XML. It is a way of using existing web-based technologies to provide a rich user interface to websites. It is a design pattern and not a new language and it is not a W3C standard.

In his article, Jesse Garrett lists the properties of Ajax:

  • standards-based presentation using XHTML and CSS
  • dynamic display and interaction using the Document Object Model
  • data interchange and manipulation using XML and XSLT
  • asynchronous data retrieval using XMLHttpRequest
  • and JavaScript binding everything together

In order for a classic web page to respond to a users input, an HTTP request needs to be sent to the server. The server processes the input and replies with an HTML page. Thus the entire page needs to be reloaded in order to provide a response to the user. This request/reply model can be tedious for a user. Ajax proposes a different model.Using the Ajax method a script can send asynchronous HTTP requests from the browser to the server. The script is notified when the response arrives at the browser, and can process the response. Units of data can be requested and processed without the user being disrupted by a complete page refresh. Garrett provides a graphical depiction of the Ajax model in the following image.

Ajax Fundamentals - Life Cycle

Continue reading

Ajax Fundamentals – About & Index

Index | Part 1 | Part 2 | Part 3 | Part 4 | Part 5

About This Series

Silverlight, Apollo, JavaFX have spurred another wave of Rich Internet Application discussions. I came across an interesting interview with David Heinemeier Hansson, the creator of Rails.

In this interview Hansson states: “We went through this with Java applets, they were going to rule the Web. Everything was going to be in a Java applet. HTML and CSS is history. And Flash came around, and Flash started focusing on applications. Now Flash is going to rule the Web and HTML and so on is yesterday. Now, Silverlight, Apollo, JavaFX, they’re all bidding to take over the JavaScript, HTML and CSS [spaces], and I just don’t buy it.”

Hanson also made this comment: “I think that there are misconceptions going on from people who are pushing these alternative delivery platforms that somehow Web developers are hungry for richer and richer experiences, that they’re really unhappy working with HTML and CSS. And that’s just not true. We’re not clamoring to re-create the desktop on the Web.”

Hansson makes a good point, developers will not be throwing away HTML and CSS any time soon. Therefore I have decided to create this series to explore the different facets of developing with Ajax.

Index

Part 1
1. Introduction to Ajax
2. The XMLHttpRequest Object
2.1. The Document Object Model
2.1.3. DOM Levels

Part 2
2. Ajax Communication
2.1. Handling the Server Response
2.2. Parsing Parameters in the Request
2.3. JavaScript Object Notation

Part 3
3. Security Issues
4. Disadvantages
4.1. Usability Problems
4.2. JavaScript Disabled
4.3. Search Engine Indexing

Part 4
5. Development and Debugging Tools
5.1. Documenting JavaScript
5.2. Firefox Tools & Extensions
5.3. JavaScript Syntax Checking
5.4. Compression and Obfuscation

Part 5
6. Summary

Index | Part 1 | Part 2 | Part 3 | Part 4 | Part 5