Tuesday, January 29

ActiveRecord Databases - II

In the previous post, I just shown how do you tell your application the whereabouts of the database(s) that's in use. Now we are left out with task to connect each tables. Let me remind you again, this would need configuring/customizing lots of xml files in java based applications.
You may ask:
Come on, How do you achieve it without the xml files?
Well the magic here is usage of, pluralisation of tables and respective singular form for it's class names.

Can you show me how to do it?
hmmm... of course.
In last post we modified database.yml of our "dummy" project.

adapter: mysql
database: dummy
username: root
password:
host: localhost

Just recollect, this shows our "dummy" project is referencing to database by name "dummy". I am creating the database related tables, objects (rows), columns (properties) using a tool called phpMyAdmin.

Assuming that this "dummy" database contains a table with user information. So our convention would suggest to have table name in plural form. Let's call it as "users". Now we need to have a class created with singular form of the "users" -> "user", and respective logic relating to the table would go into/under this class.
class User <>

end

Let us diagnose a bit the above code. Recollect the convention we talked above, and the ORM concept. This means that the applications having class called "User" which would connect/contact to database table by name "users" (the database info is set up in database.yml).

We will slowly getting into the code and we keep developing or adding more functionalities to our "dummy" project.

Do I need to use only mysql as the database?
Not exactly and need not be. The following table would give the info related to configure each database and the respective parameters:


Well more action and fun is on the way :)

Monday, January 28

ActiveRecord Databases - I

One of the main features that rails do support on is Convention over Configuration. Well repeat again and again Convention over Configuration. Let it get into the minds!
Well it is spread across the rails framework with which will be developing an application. I will be reminding whenever it's put in use.
In previous post, I did stress on how simple it would be in configuring the databases and tables with your application. In Java based applications, this would be done using lot of xml files, which is of course, time taking, lot of repetitive work and error prone... (at least that's what my friend's used to say!).

Well in rails this is not the case a simple convention that you follow would ensure of configuring the tables of databases.
"You name the tables in database as plurals and create classes with singular form of the table names."
Configuring the Databases:
The choice of which database you use the configuration and respective adapter would depend on. When we created an application, there is a set of predefined folders created over a simple command! (I will touch upon this later). "config" is one such folder and under this we will now concentrate/repair on "database.yml".
Rails would automatically create 3 different environments:
  1. Development
  2. Test
  3. Production
Based on the environment we work on we need to edit the data accordingly. (More on environments will be covered sooner!)
This file contains the information relate to the adapter, database, user credentials, host, port...

This does make sense in a way, the plural form for tables will fit as it contains huge data and the respective class which we would be placed under app/models, with the extension ".rb" is named in singular form.


development:
adapter: mysql
database: dummy
username: root
password:
host: localhost

What it means?
Our application is connected to MySQL database by name dummy, user being and root and with an empty password. The host environment is "localhost".

To Be Continued...

Web Applications

Database is one of the key things for the web applications. The flow of web application can be simply put into the following broad steps:

  • User makes request from Browser/Client
  • The "http" request carries this to Server (web/app server)
  • The web server parts the request with the help of CGI/FCGI...
  • CGI/FCGI gives the control to application
  • Application takes the rest of game, which include
    • Identifying the actions/method
    • Actions/Methods would do the logic
    • Contacts the database
    • Fetches the data and pushes to front (with appropriate html's...)
  • The server would redirect the same to client side.
  • The user gets the content he asked for.
That would give good picture on how the web application work.
The above points give us information on what are the components that are required and each of them will be covered in the posts coming upon!

Friday, January 18

Ruby on Rails - ActiveRecord pattern

We always talk about programming languages and we take pride in propagating how the language follows/supports the object oriented paradigm. This really makes sense, since we can connect them to real time objects. But, what about the databases? All the web applications do require some databases to store the content, user information and so on. We alway depend on database for any kind of information, but
Are our databases are ready to listen to objects?
How the languages communicate to the database (nothing but content)?
Well this is where the Active Record pitches in: Active record is an approach that is used to access the data.
How it does?
Programming Language Database
class =====> table
object =====> single row in table
properties/methods =====> columns in table

"A database table or view is wrapped into a class, thus an object instance is tied to a single row in the table. After creation of an object, a new row is added to the table upon save. Any object loaded gets its information from the database; when an object is updated, the corresponding row in the table is also updated. The wrapper class implements accessor methods or properties for each column in the table or view."

Now that is with Active record. Rails do implement the same pattern and with power of ruby, it does add some extra features/conventions to make developers life simpler.

Well in following posts we will see,
  1. How active record is implemented in rails
  2. What are the conventions?
  3. How to configure database to rails applications?
  4. Do we need to write xml files to configure each table?

Wednesday, January 16

@ Ruby on Rails conferences

I have been into Open Source technologies from starting of my career and I always take pride to speak about the technologies, I had been into. Be it:
Browser - Firefox, Mozilla...
Testing tools - Selenium...
Programming Languages - PHP, Ruby, Python...

and the list goes on and on.

Recently I had been associated with open source community, where I had chance to speak about the open source technologies I work on: Ruby, Rails, Aptana...
You can find more about community here and the following links shows my participation:

Tuesday, January 15

Ruby on Rails - Installing Rails

Recently my laptop crashed as the virus invaded to each and every folder possible. I could not open any of local folders, files and also not able to access the internet. I was so fed up, without second thought I just reformatted my system. Of course, later I realized the value of backup, when I was going through the installations.
Adding to this when I tried to install rails through "gem install rails --include-dependencies". It was annoying message, which said the request to remote server timed out!

Well I was just discussing with my juniors what exactly rails consists/made of?
Rails is nothing but Web-application framework with template engine, control-flow layer, and ORM.
I also explained that they are nothing but few ruby files called/named as gems.
activeresource, rails, activesupport, activerecord, actionpack,
I recollected that, and instead of depending on net connection speed, went to ruby forge and picked up all the above gems (latest version 2.0.2) and stored on to local folders. Then installed one by one in the order... (click the links to download)
  1. activeresource 2.0.2
  2. rails 2.0.2
  3. activesupport 2.0.2
  4. activerecord 2.0.2
  5. actionpack 2.0.2
  6. actionmailer 2.0.2
Download the archive.
Note: The order is maintained based on the dependencies the other
So this is what downloaded/installed when you run the command "gem install rails --include-dependencies".


Though each of the above listed gems could become a topic by itself, let me brief what's the role each of them got to play:
  • activeresource - Think Active Record for web resources.
  • rails - Web-application framework with template engine, control-flow layer, and ORM.
  • activesupport - Support and utility classes used by the Rails framework.
  • activerecord - Implements the ActiveRecord pattern for ORM.
  • actionpack - Web-flow and rendering framework putting the VC (Views & Controllers) in MVC
  • actionmailer - Service layer for easy email delivery and testing.
The embedded image shows the list of gems that will be installed, when you install ruby, rails.

Thanks to my friend Manoj for the screenshot.
Cross check:
  1. ruby -v => To check the version of ruby installed
  2. gem -v => To check the version of gems installed
  3. rails -v => To check the version of rails installed
  4. gemlist => To find the list of all gems installed

Monday, January 14

Ruby on Rails Hosting - Heroku!

In my last post I discussed on the way we create 'class' and the Object Oriented paradigm in general.
Let me remind all again, this course is structured to provide enough information on ruby such that it would help to take a loot on Ruby on Rails. Stressing again on the importance of Ruby on Rails, an MVC architecture based framework, a well organised, easily maintainable (no mess whatsoever!)... which all mean faster production and rest all...

I thought I would start creating some basic web applications based on ror, before that I want to bring notice to all about Hosting an application.

To host any application it requires an Application/web server, CGI/fCGI, and the environment in which you application is developed and the related databases and plug ins/vendor software (if any used!).

The good news is that you have we need not go through this entire process of install, setting up things, configuring things etc.,

Heroku :
Heroku is an online hosting environment for the rails based web applications. Not just that it come out with pretty good number of features like editing application online, export and importing the existing rails applications, customising the url's, share and collaborate online the rails projects...

Have a look at this !

Disclaimer:
Please do contact the Heroku team if you have queries on privacy and other issues.

Thursday, January 10

Ruby Classes - 1

Ever since the languages have come up with approach of problem centric not just the system centric, we have been hearing about these Objects. Since our daily life is around, with objects this would ease our understanding the problems, solving the problems.
As we know Ruby is pure object oriented language (no datatypes, all are treated as objects), and the Object Oriented paradigm very well fits with Ruby too!

* Abstraction
* Encapsulation
* Inheritance
* Polymorphism

So how the classes come into picture ?
Well a category(group) of objects like (similar) is called a class
Classes hold the properties, characteristics and the actions that are done by objects. This acts as constructor to create more such objects. And we all know that the objects in the real world communicate with each other, similarly here we have the actions/methods doing the job of communication across objects of different classes.

In ruby the class will look like this:

Download Examples on Classes
Example 1: Classes.

class ClassOne

def do_something

puts ("I am displayed")

end


end



c1 = ClassOne.new
c1.do_something


# Observe:
# --> The class starts with "class" (all lower case) keyword and concludes with "end" keyword.
# --> The class name starts with Capital/Multi-word written using CamelCase (ClassOne)
# --> The (.new) is the method that would create multiple copies of objects belongs to a class.
# --> Once the object is created(c1), it gain access to all the methods(dosomething) defined within the class.
# --> The method name starts with lowercase (just convention) and multi-word separated with 'underscore'.

Download Examples on Classes
Example 2: Shows passing parameters to methods.

# Class is like a blueprint from which individual objects are constructed.
# Methods/Definitions/Actions are the means of communication between the objects.

class ClassOne

def do_something(doing)
puts ("I am #{doing}")
end

def someone

puts "I am not public but private"
end

end


c1 = ClassOne.new
c1.do_something("singing")
c1.do_something("listening")
c1.someone

# Observe:
# Passing parameters across objects to actions
# --> The class starts with "class" (all lower case) keyword and "end" is the end of the class.
# --> The class name starts with Capital/Multi-word written using camelcase
# --> The (.new) is one of the methods that would create multiple copies of objects belongs to a class.
# --> Once the object is created(c1), it gain access to all the methods(dosomething) defined within the class.
# --> The method name starts with lowercase (just convention) and multi-word separated with 'underscore'.

Download Examples on Classes

Web Application resources required Ruby vs Java

David Heinemeier Hansson says,
"Once you've tried developing a substantial application in Java or PHP or C# or whatever, the difference in Rails will be readily apparent. You gotta feel the hurt before you can appreciate the cure."


Who is David Heinemeier Hansson? David is...
What else he said about Ruby on Rails? Interview with David...
How popular he is? Well he ranked ...

Monday, January 7

Ruby vs Java

Ruby on Rails Arrays and Hashes

Download the Examples
Arrays

Ruby has Arrays and Hashes to store/collect the objects.
And these objects are accessed using an index.

Array:
1. It is an ordered collection of objects.
2. Indexed with integers.

How to create an Array?
Answer is there are three different ways to create an array.
# Way 1 :
a1 = []

# Crosscheck whether we created the array "a1".
puts "a1 is an #{a1.class}"

# Way 2 :
a2 = [1,2,3]

# Crosscheck whether we created the array "a2".
puts "a2 is an #{a2.class}"

# Way 3 :
a3 = Array.new

# Crosscheck whether we created the array "a3".
puts "a3 is an #{a3.class}"


# Note:
# --> The array holds the objects within square brackets.
# --> The multiple objects separated with commas.
# --> The array holds different objects (int, float, string...).
# --> Way 1, creates an empty array.
# --> Way 2, creates an array with few objects defined/collected.
# --> Way 3, creates an empty array using ".new" operator/method.
# --> At any point to check whether we created array's or not, we can use ".class".

Exercise:
Well following are the built in methods that we can apply on to arrays.
&, *, +, -, <<, <=> , ==, [], [], []=, abbrev, assoc, at, clear, collect, collect!, compact , compact!, concat , dclone , delete, delete_at, delete_if, each, each_index, empty? , eql?, fetch , fill, first, flatten , flatten!, frozen? , hash include?, index , indexes, indices, initialize_copy , insert, inspect , join, last, length, map , map!, new, nitems , pack , pop, pretty_print, pretty_print_cycle, push , quote, rassoc, reject , reject!, replace, reverse, reverse! , reverse_each , rindex , select, shift, size , slice, slice!, sort , sort!, to_a , to_ary , to_s , to_yaml, transpose, uniq , uniq! , unshift, values_at, yaml_initialize, zip , .

Download the Examples

Hashes :


Ruby has Arrays and Hashes to store/collect the objects.
And these objects are accessed using an index.


# How to create an Hash?
# Answer is there are three different ways to create an Hash.
# Way 1 :
h1 = {}

# Crosscheck whether we created the Hash "h1".
puts "h1 is a #{h1.class}"

# Way 2 :
h2 = {
"Object1"=>"First Object",
"Object2"=>"Second Object"
}

# Crosscheck whether we created the Hash "h2".
puts "h2 is a #{h2.class}"

# Way 3 :
h3 = Hash.new

# Crosscheck whether we created the Hash "h3".
puts "h3 is a #{h3.class}"


# Note:
# --> The hash hold objects within curly braces.
# --> The Key and Value pair forms an object in Hash.
# --> The multiple objects separated with commas.
# --> The hash holds different data types.
# --> Way 1, creates an empty Hash.
# --> Way 2, creates an Hash with few objects defined/collected.
# --> Way 3, creates an empty Hash using ".new" operator/method.
# --> At any point to check whether we created Hash or not, we can use ".class".

Exercise on Hashes:

==, [], [], []=, clear, default, default=, default_proc, delete, delete_if, each, each_key, each_pair, each_value, empty?, fetch, has_key?, has_value?, include?, index, indexes, indices, initialize_copy, inspect, invert, key?, keys, length, member?, merge, merge!, new, pretty_print , pretty_print_cycle, rehash, reject, reject!, replace, select, shift, size, sort, store, to_a, to_hash, to_s, to_yaml, update, value?, values, values_at, yaml_initialize

Download the Examples
The zip file contains examples on Creating Arrays and Hashes, Methods implemented on arrays.
Note:
  1. Please comment/un comment the wanted/un necessary puts, for better understanding.