Friday, April 16, 2010

Workshop 4: Riding the Rails with Ruby

Topic objectives
• To learn about the Ruby language and its classes and methods;
• To use Ruby via an interpreter console window with Windows, Linux or MacOS
• To select and test a Ruby IDE
• To explain how Rails framework is built upon inheritance of Ruby classes and methods.


To do:

1. Spend some time moving your way through the 46 Ruby coding examples in the Ruby Tutorial with Code from http://www.fincher.org/tips/Languages/Ruby/
2. What are the syntax differences in the way that Ruby and Javascript use the if statement?

The main syntax different between Ruby and JavaScript using the "if" statement is that the "else if" condition in Ruby is stick together as "elseif" and there is not () brackets for condition statement and no {} brackets for the if else statement. Both if else conditional sample codes are attached as follows.

Ruby:
if var == 10
print “Variable is 10″
elsif var == “20″
print “Variable is 20″
else
print “Variable is something else”
end

JavaScript:
if (time < 10)
{
document.write("Good morning!");
}
else
{
document.write("Good day!");
}


3. While Ruby and Python are quite similar, can you find some similarities between Ruby and Javascript?

JavaScript and Ruby are very similar in many aspects, but they are also very different In some areas. Both languages are highly dynamic, allowing you to change objects and methods at runtime and both languages are very object-oriented. Both can use variables to hold data and reference to other objects.

In JavaScript we use function to provide scope. This means that for and while loops, for example, do not have their own scope. this is the same In Ruby, but while Ruby has classes and modules to provide shelter from the global scope.

There are two methods in JavaScript which are "call" and "apply". These methods allow you to call a function. With "call", you give it the arguments like you would when calling it directly but with "apply" you pass the arguments as an array. The "apply" version is similar to "splatting" an array in a similar situation in Ruby.

The concept of class method for both JavaScript and Ruby are the same which instantiates a new object from that class. The classes are also "open" and you can extend any class with new methods for both.


Recommended time: 1-4 hours, but it may take several trial attempts so be patient with initial success.



Challenge Problems:

1. Create, test and debug a Ruby program called dognames.rb or catnames.rb to accept 3 names from the keyboard and to display each name on the screen in alphabetical order WITHOUT using a data structure such as a list.

The code is created as below:

def dognames
puts "Enter the first dog name: "
$dogname1 = gets
puts "Enter the second dog name: "
$dogname2 = gets
puts "Enter the third dog name: "
$dogname3 = gets

if $dogname1 > $dogname2
$temp = $dogname1
$dogname1 = $dogname2
$dogname2 = $temp
end

if $dogname2 > $dogname3
$temp = $dogname2
$dogname2 = $dogname3
$dogname3 = $temp
end

if $dogname1 > $dogname2
$temp = $dogname1
$dogname1 = $dogname2
$dogname2 = $temp
end

puts "Dog names in alphabetical order:"
puts $dogname1, $dogname2, $dogname3

end
dognames

The above code is saved to file dognames.rb. It is tested and debugged by making use of the Ruby Interpreter (C:\Ruby\bin\irb.bat) and issue the command "irb dognames.rb" which successfully generates the desired result as follows:




2. Write a Ruby program called fizzbuzz.rb that prints the numbers from 1 to 100. But for multiples of three print "Fizz" instead of the number and for the multiples of five print "Buzz". For numbers which are multiples of both three and five print "FizzBuzz".

The code is created as below:

def fizzbuzz

1.upto(100) do |i|
if i % 5 == 0 and i % 3 == 0
puts "FizzBuzz"
elsif i % 5 == 0
puts "Buzz"
elsif i % 3 == 0
puts "Fizz"
else
puts i
end
end
end

fizzbuzz


Part of the output is generated as follow:





Compare the Ruby and Python versions of the dog years calculator:

#!/usr/bin/ruby
# The Dog year calculator program called dogyears.rb

def dogyears
# get the original age
puts “Enter your age (in human years): "
age = gets # gets is a method for input from keyboard
puts # is a method or operator for screen output

#do some range checking, then print result
if age < 0
puts "Negative age?!? I don't think so."
elsif age < 3 or age > 110
puts "Frankly, I don't believe you."
else
puts "That's", age*7, "in dog years."
end
dogyears

Python

#!/usr/bin/python
# The Dog year calculator program called dogyears.py

def dogyears():
# get the original age
age = input("Enter your age (in human years): ")
print # print a blank line

# do some range checking, then print result
if age < 0:
print "Negative age?!? I don't think so."
elif age < 3 or age > 110:
print "Frankly, I don't believe you."
else:
print "That's", age*7, "in dog years."

### pause for Return key (so window doesn't disappear)
raw_input('press Return>')

def main():
dogyears()
main()


After comparing the Ruby and Python code which perform the same function to calculate the dog age by multiplying the human age by 7, it is found that the logical flow and syntax is very familiar. With only some minor syntax difference for the If … Else condition. Also Python requires additional code to pause the output screen.



Reference

How-To Greek. (2010). Ruby IF, Else If Command Syntax. Retrieved 15 Apr, 2010, from http://www.howtogeek.com/howto/programming/ruby/ruby-if-else-if-command-syntax/

W3schools.com. (2010). JavaScript If…Else Statements. Retrieved 15 Apr, 2010, from http://www.w3schools.com/js/js_if_else.asp

Sneaky Abstractions. (2010).JavaScript eye for the Ruby Guy. Retrieved 15 Apr, 2010, from http://tore.darell.no/pages/javascript_eye_for_the_ruby_guy

Wednesday, April 14, 2010

Elevator Pitch 1

Hi, I am Gary studying in Hong Kong. E-System Infrastructure Development, my first impression is a subject for system administrator or project manager. The time when I received the subject guide really surprises me… Frankly speaking, I am not studying or working as a system developer at the very beginning, but as a system administrator. The first assessment is already a great challenge for me. I could barely make up the schedule to finish all the exercises and workshops. But in return, I have learnt a lot about building a e-commerce web site either from the ICT manager, system architect or developer aspect. The step-by-step guide of the exercises also guide me through the most popular design model and tools to build an interactive site that serve commercial purpose. It equips me with knowledge not only as a developer but also as a system architect. Couldn’t find another course as update and useful as this. Second assessment is on the way, hope I could finish successfully and graduate. Thanks for listening.

Monday, April 12, 2010

Workshop 3: Online Taxi Booking System: MySQL and Database design

Topic objectives
• Develop a database object design for an online taxi booking system (OTBS);
• Revise database techniques with Rails and SQL
• Describe how to use the MVC “push-based architecture” in the Ruby on Rails development environment

To do:

1. Set up the MySQL tools on your computer as described in section 6 above.

The MySQL server 5.1 is downloaded from http://www.mysql.com and installed into my laptop as follows:




2. Rails will setup a new application directory for each of your Web application projects. Get InstantRails (Windows) or Locomotive (MacOS) running on your machine. Both packages install Ruby, Rails, a Web server or one called ‘Mongrel’ or another small Ruby Web server called ‘WEBrick’, and MySQL “inside a bubble” as I call it so that others parts of your system are not modified (Similarly ZOPE does with installing its own Web server and Python versions).

Ruby on Rails installer for Windows 1.8.7 package is downloaded from http://www.rubyonrails.org and installed.

Command “gems install rails --include-dependencies” is issued to install GEMS. Another command “gem update rails” is also required to grab the most recent updates from the official web.


3. Once Rails is running you at http://localhost:3000, you need to configure database access. Connection to the database is specified in the config/database.yml file.

“Rails Taxi” command is used to generate the data model for the Taxi project with the following hierarchy

C:\Ruby>rails Taxi
create
create app/controllers
create app/helpers
create app/models
create app/views/layouts
create config/environments
create config/initializers
create config/locales
create db
create doc
create lib
create lib/tasks
create log
create public/images
create public/javascripts
create public/stylesheets
create script/performance
create test/fixtures
create test/functional
create test/integration
create test/performance
create test/unit
create vendor
create vendor/plugins
create tmp/sessions
create tmp/sockets
create tmp/cache
create tmp/pids
create Rakefile
create README
create app/controllers/application_controller.rb
create app/helpers/application_helper.rb
create config/database.yml
create config/routes.rb
create config/locales/en.yml
create db/seeds.rb
create config/initializers/backtrace_silencers.rb
create config/initializers/inflections.rb
create config/initializers/mime_types.rb
create config/initializers/new_rails_defaults.rb
create config/initializers/session_store.rb
create config/environment.rb
create config/boot.rb
create config/environments/production.rb
create config/environments/development.rb
create config/environments/test.rb
create script/about
create script/console
create script/dbconsole
create script/destroy
create script/generate
create script/runner
create script/server
create script/plugin
create script/performance/benchmarker
create script/performance/profiler
create test/test_helper.rb
create test/performance/browsing_test.rb
create public/404.html
create public/422.html
create public/500.html
create public/index.html
create public/favicon.ico
create public/robots.txt
create public/images/rails.png
create public/javascripts/prototype.js
create public/javascripts/effects.js
create public/javascripts/dragdrop.js
create public/javascripts/controls.js
create public/javascripts/application.js
create doc/README_FOR_APP
create log/server.log
create log/production.log
create log/development.log
create log/test.log

Change to the Taxi directory C:\Ruby\Taxi and issue the command “ruby script/server” to run WEBrick web server on the machine and to test if the environment is ready or not.

C:\Ruby\Taxi>ruby script/server
=> Booting WEBrick
=> Rails 2.3.5 application starting on http://0.0.0.0:3000
=> Call with -d to detach
=> Ctrl-C to shutdown server
[2010-04-15 10:03:32] INFO WEBrick 1.3.1
[2010-04-15 10:03:32] INFO ruby 1.8.7 (2010-01-10) [i386-mingw32]
[2010-04-15 10:03:32] INFO WEBrick::HTTPServer#start: pid=3444 port=3000


If the environment is setup successfully it would show the following.



The connection of database is required to be specified in the file which is located in C:\Ruby\Taxi\config\database.yml with the following content.





4. Generate the Passenger model by creating the MySQL database and ‘passengers’ table from the information above.

There is a tool for GUI interface to manage MySQL called MySQL-Front is downloaded and installed. Database “Taxi” is created with table “Passenger” inserted. The required field for the table is also inserted according as follows.




5. Further work on understanding MySQL under Rails by David Mertz:
a. See “Fast-track your Web apps with Ruby on Rails” at http://www-128.ibm.com/developerworks/linux/library/l-rubyrails/
b. The “Rolling with Ruby on Rails” series and “Cookbook recipes by Curt Hibbs and others beginning at http://www.onlamp.com/pub/a/onlamp/2005/01/20/rails.html

Both resources links has been reviewed. I would find the second link to be extremely useful and practical for this Workshop which is a hands on step-by-step guide to setup the RoR environment with the association to the database MySQL. It also mentioned the tools for managing MySQL in depth which is very useful for students like me who is not a DBA typing SQL query commands everyday.


Recommended time: 1-4 hours, but it may take several trial attempts so be patient with initial success.

Challenge Problems: There are enough already in this workshop.

Sunday, April 11, 2010

Exercise 8: XML Introduction

Create an XML document for an online catalogue of cars where each car has the child elements of make, model, year, colour, engine, number_of_doors, transmission_type and accessories. The engine has child elements called number_of_cylinders and fuel_system

Saturday, April 10, 2010

Exercise 7: Application server platforms in e-commerce

1. Why is the perception getting stronger that integration will become a critical factor in coming days?

Application integration is the process of bringing data or function from one application program together with that of another application program where these programs already exist. The process is sometimes accomplished by using middleware, either packaged by a vendor or written on a custom basis.

The integration of function or data across different application platforms is increasingly import because it provides users with the ability to manipulate legacy data and to easier to acquire and maintain new data. Users could take advantage of familiar software to use known assets and resources and to use existing data management tools to access data wherever it is located. Users can work with a single, tailored user interface which is available through virtually any device which allows coherent search, access, replication, transformation and analysis over a unified view of information assets to meet business needs.


2. What is the relationship of AJAX to JQuery (jquery.com) and the lightweight Web2.0 JavaScript framework called MooTools (mootools.net) within the enterprise software architecture?

AJAX = Asynchronous JavaScript +XML, which is a group of interrelated web development techniques used on the client-side to create interactive web applications. With AJAX, web applications can retrieve data from the server asynchronously in the background without interfering with the display and behavior of the existing page. This is accomplished by using existing technologies together including HTML, XHTML, CSS, JavaScript, DOM, XML, XSLT and XMLHttpRequest object.
jQuery is a lightweight cross-browser JavaScript library that emphasizes interaction between JavaScript and HTML. The syntax of jQuery is designed to make it easier to navigate a document, create animations, handle events and develop AJAX applications. Microsoft has bundled jQuery on their platforms for adopting it with AJAX framework. Microsoft hosts jQuery on its AJAX content delivery network making it easy to add the support for jQuery library.


It is possible to perform browser-independent AJAX queries using $.ajax and associated methods to load and manipulate remote data.

$.ajax({
type: "POST",
url: "some.php",
data: "name=John&location=Boston",
success: function(msg){
alert( "Data Saved: " + msg );
}
});

JavaScript is a client-side scripting language that can be used for implementing an AJAX application. It is the most popular language for AJAX programming due to its inclusion in and compatibility with the majority of modern web browsers. Classic AJAX involves writing ad-hoc JavaScript on the client. It is a simpler alternative to use standard JavaScript libraries that can partially update a page.


3. What are the similarities between the object-oriented development using model-view-controller (MVC) in Ruby on Rails 2.0 and Action Script 2.0 (Flash animations)?

Rails use the Model-View-Controller (MVC) architecture pattern to organize application programming. The MVC architecture with the Controller handles the input event from the user interface and notifies the Model of the user action. The View gets its data from the Model and render itself. It seperates into various packages namely ActiveRecord which is an object-relational mapping system for database access. Apart from standard packages, developers can make plugins to extend existing packages. The Convention over Configuration (CoC) and the rapid development principle of Don’t Repeat Yourself (DRY) emphasis less coding and less repetition effort by developer.

ActionScript is a scripting language based on ECMAScript which is used primarily for the development of websites and software using the Adobe Flash Player platform in the form of SWF files embedded into web pages. ActionScript 2.0 also introduced class-based inheritance syntax so that developers could create classes and interfaces, much as they would in class-based languages such as Java and C++. These allow for a more structured object-oriented programming approach for code reuse.


4. What does it mean to develop RESTful practices into our web applications?

Representation State Transfer (REST) is a style of software architecture for distributed hypermedia systems such as the World Wide Web. Confirming to the REST constraints is referred to as being “RESTful”.

REST-style architectures consist of clients and servers. Clients initiate requests to servers. Server process requests and returns appropriate responses. Requests and responses are built around the transfer of “representations” of “resources” in stateless client-server architecture. REST is an analytical description of the existing web architecture in which the web services are viewed as resources. It also has to be cacheable, layered system with enhanced scalability and performance.
RESTful practice is especially useful when the web service is completely stateless and the bandwidth is particularly important and needs to be limited. REST is particularly useful for limited-profile device such as PDAs and mobile phones.

Reference
SearchSOA.com Definitions (Application Integration. (2003). Retrieved 4 Apr, 2010, from http://searchsoa.techtarget.com/sDefinition/0,,sid26_gci211586,00.html

DB2 Universal Database. (2009). Why is information integration important to your enterprise? Retrieved 4 Apr, 2010, from http://publib.boulder.ibm.com/infocenter/db2luw/v8/index.jsp?topic=/com.ibm.db2.ii.doc/ad/ciiwhyen.htm

Mozilla Developer Center. (2010). AJAX. Retrieved 4 Apr, 2010, from https://developer.mozilla.org/en/AJAX

Wikipedia. (2010). AJAX (programming). Retrieved 4 Apr, 2010, from http://en.wikipedia.org/wiki/Ajax_(programming)

Wikipedia. (2010). jQuery retrieved 4 Apr, 2010, from http://en.wikipedia.org/wiki/Jquery

Wikipedia. (2010). ActionScript. Retrieved 4 Apr, 2010, from http://en.wikipedia.org/wiki/ActionScript

Wikipedia. (2010). Ruby on Rails. Retrieved 4 Apr, 2010, from http://en.wikipedia.org/wiki/Ruby_on_rails

Oracle Sun Developer Network. (2010). RESTful Web Services. Retrieved 4 Apr, 2010, from http://java.sun.com/developer/technicalArticles/WebServices/restful/

Tuesday, April 6, 2010

Exercise 6: Web form design and processing: A basis for e-commerce interaction

1. Design the form
“Retrofit” the form data string above:
Name=Evan+Burke&card=Visa&number=8443261344895544&order=French+perfume
For buying some French perfume into the
HTML form fields and submit button on the Web page form.



2. Write the script
Script archives exist for PERL, Python and JavaScript. Search the Web for a script that processes the HTML forms data. Read the code and list the steps involved in processing the form.

The following JavaScript is called a function called SubmitForm which would be executed when the submit button is clicked in the process.html.




3. Can you modify the script to process the form?
With JavaScript at the client side we can process simple forms without invoking server. JavaScript can only take care all the preliminary requirements, such as validating input to ensure that the user has entered everything and trigger JavaScript events by manipulating form controls. To actually process the form, CGI is required which is a mechanism for safely transporting data from a client HTML form to server.


4. Improve the user experience by add a JavaScript feature.

The following script checks for any input box in the form which is not filled in and prompt to alert the user to fill in the specific input box.

function checkscript() {
for (i=0;i<4;i++) {
box = document.example.elements[i];
if (!box.value) {
alert('You haven\'t filled in ' + box.name + '!');
box.focus()
return false;
}
}
return true;
}


Reference
Gordon, M. (1996). Using JavaScript and forms. Retrieved at 2 Apr, 2010 from http://www.javaworld.com/jw-06-1996/jw-06-javascript.html

Dutch politics primer and blog (2010). Example Form. Retrieved at 2 Apr,2010 from http://www.quirksmode.org/js/formex.html

Sunday, April 4, 2010

Workshop 2: Model View Controller design approach

Topic objectives
• Describe the history and architecture of the Model View Controller (MVC) approach to Web application design;
• Revise database techniques with Rails and SQL
• Describe how to use MVC in the Ruby on Rails development environment
• Set up a focus group (like a study group for peer learning) to work on the Ruby on Rails workshops via Interact tools

To do:

1. Set up a focus group (like a study group for peer learning) to work on the Ruby on Rails workshops via Interact tools as a class.

Focus group is setup in CSU Interact Forum where I have joined the discussion on the topics raised by other students and has looked into the problem raised by course coordinator and figure out the solution by web searching.

2. What is meant by “convention over configuration” and how does it reduce coding?

“Convention over configuration” (CoC) means a developer only needs to specify unconventional aspects of the application. For example, if there is a class Sale in the model, t he corresponding table in the database is called sales by default. It is only if one deviates from this convention, such as calling the table “product_sold”, that one needs to write code regarding these names.

When the convention implemented by the tool you are using matches your desired behavior, you enjoy the benefits without having to write configuration files. These reduce repeated coding and configuration. Only when your desired behavior deviates from the implemented convention, then you configure your desired behavior.


3. Further work on understanding MVC:
a. See the wiki at http://wiki.rubyonrails.org/rails/pages/UnderstandingMVC
b. Do the MVC tutorial at http://wiki.squeak.org/squeak/1767

Having walkthrough the wiki materials about MVC. Understood that MVC stands for Model-View-Controller and it is one of the earliest and one of the most successful design patterns. With the View rendering the graphical and textual output of the application. The Controller interprets the mouse and keyboard inputs from the user. The Model manages the behavior and data of the application, responds to requests for information about its state and responds to instructions to change state.

4. Got a spare hour or so? I recommend the UC Berkeley RAD lab’s Ruby on Rails Short course at http://youtube.com/watch?v=LADHwoN2LMM
Read the Flash article using ActionScript by Colin Moock titled “The Model-View-Controller Design Pattern “at http://www.adobe.com/devnet/flash/articles/mv_controller.html

A really long video which would take 6 hours for an undergraduate course topic on Ruby-on-Rails. It is a step-by-step approach to guide your through RoR with lab sessions. Really useful for beginners who need to have a quick introductory course and get it done within one day.



Challenge Problems:

1. How is Rails structured to follow the MVC pattern?

Consider our project and examine the directories where Rails is located. If the data model is called Taxi (it is convention to name the model beginning with an upper case letter). The model is a Ruby class located in app/models/taxi.rb
The SQL table is taxis – the pluralisation of the model. In our project we have 2 tables as passenger_origin and passenger_destination, where the table row = an object instance and each of the columns = an object attribute.

The controller methods live in app/controllers/taxi_controller.rb
Each controller can access templates to display the input screen and methods for action.

The views are kept is app/views/taxi/*.rhtml, where each *.rhtml maps to a controller method.

In Rails, the view is rendered using RHTML or RXML. According to the wiki page at http://wiki.rubyonrails.org/rails/pages/UnderstandingViews, RHTML is HTML with embedded Ruby code and RXML is Ruby-generated XML code.

The data model “Taxi” is created by issuing the following command

C:\Ruby>rails Taxi
create
create app/controllers
create app/helpers
create app/models
create app/views/layouts
create config/environments
create config/initializers
create config/locales
create db
create doc
create lib
create lib/tasks
create log
create public/images
create public/javascripts
create public/stylesheets
create script/performance
create test/fixtures
create test/functional
create test/integration
create test/performance
create test/unit
create vendor
create vendor/plugins
create tmp/sessions
create tmp/sockets
create tmp/cache
create tmp/pids
create Rakefile
create README
create app/controllers/application_controller.rb
create app/helpers/application_helper.rb
create config/database.yml
create config/routes.rb
create config/locales/en.yml
create db/seeds.rb
create config/initializers/backtrace_silencers.rb
create config/initializers/inflections.rb
create config/initializers/mime_types.rb
create config/initializers/new_rails_defaults.rb
create config/initializers/session_store.rb
create config/environment.rb
create config/boot.rb
create config/environments/production.rb
create config/environments/development.rb
create config/environments/test.rb
create script/about
create script/console
create script/dbconsole
create script/destroy
create script/generate
create script/runner
create script/server
create script/plugin
create script/performance/benchmarker
create script/performance/profiler
create test/test_helper.rb
create test/performance/browsing_test.rb
create public/404.html
create public/422.html
create public/500.html
create public/index.html
create public/favicon.ico
create public/robots.txt
create public/images/rails.png
create public/javascripts/prototype.js
create public/javascripts/effects.js
create public/javascripts/dragdrop.js
create public/javascripts/controls.js
create public/javascripts/application.js
create doc/README_FOR_APP
create log/server.log
create log/production.log
create log/development.log
create log/test.log

Currently there are no views rendered and so there is no rhtml under the C:\Ruby\Taxi\app\views\taxi. Also checked the wiki link at rubyonrails.org about understanding Views is already unavailable.

2. Apply the MVC design approach to our Project: Online Taxi Booking System.

HINT: Begin with a single model, single view and single controller classes. This will give you a head start to the next workshop: Online Taxi Booking System: SQL and Database design

Model – Defines how the system handles the passengers’ data including their names, source and destination. The action is to save the data into the database and acknowledge user the data is successful save after user click the submit button.

View – Defines what the passenger would see as they access the system, input the data and submit the data.

Controller – Receives the input from the passenger and initiate the response / acknowledgement by making calls on Model which would trigger the View to render the image to acknowledge the passenger the order has been received by the system.