Wednesday, December 3, 2008

Most useful tutorials to develop web application using Ruby on Rails

Some of my friends asked me how he/she can develop web application using Ruby on Rails. So I have written following two articles about web development using Ruby on Rails:

Also, I am sharing some tutorials that I found most useful to develop web application using Ruby on Rails which is listed below:

Hopefully above articles and tutorial will be very helpful for anyone to develop web application using Ruby on Rails. For any other help contact with me, I will be pleased to help you.

Sunday, November 30, 2008

How can I create sample application using Ruby on Rails?

To create a sample web application using Ruby on Rails needs to setup environment first which I explain in my previous blog. Now we will create a sample application to manage (CRUD) user information by using NetBeans IDE.

Below are the steps to create a sample application:
  • In the NetBeans IDE, choose File > New Project.
  • Select Ruby in the Categories field and Ruby on Rails Application in the Projects field. Click Next.
  • Type sampleapplication in the Project Name field.
  • Select Ruby as a platform in place of JRuby in Ruby Platform field. Accept all the other default settings.
  • Click Finish to create the new project. You will see a list of files in the project directory and database.yml file in the editing area.
  • Create a sample database and edit the database.yml by providing the database information in the development configuration.
  • Save the database.yml file.

Creating Model, View, Controller and migration script for user management:
  • Go to the project folder from command prompt and run following command:
    ruby script/generate scaffold user name:string email:string address:text phone:string
    It will create model, views, controller and migration script in respective directory in your project and below is the output for the command:
    exists  app/models/
    exists  app/controllers/
    exists  app/helpers/
    create  app/views/users
    exists  app/views/layouts/
    exists  test/functional/
    exists  test/unit/
    create  test/unit/helpers/
    exists  public/stylesheets/
    create  app/views/users/index.html.erb
    create  app/views/users/show.html.erb
    create  app/views/users/new.html.erb
    create  app/views/users/edit.html.erb
    create  app/views/layouts/users.html.erb
    create  public/stylesheets/scaffold.css
    create  app/controllers/users_controller.rb
    create  test/functional/users_controller_test.rb
    create  app/helpers/users_helper.rb
    create  test/unit/helpers/users_helper_test.rb
    route  map.resources :users
    dependency  model
    exists    app/models/
    exists    test/unit/
    exists    test/fixtures/
    create    app/models/user.rb
    create    test/unit/user_test.rb
    create    test/fixtures/users.yml
    create    db/migrate
    create    db/migrate/20090504184109_create_users.rb
  • In the Projects window, right-click the sampleapplication node and choose
    Migrate Database > To Current Version.
    Notes: If it generates error then run gem install mysql command from command prompt and copy libmySQL.dll from C:\Program Files\MySQL\MySQL Server 5.0\bin to C:\ruby\bin.

Run and test the Application:
  • Open routes.rb under configuration node of project folder.
  • Edit following line by removing # and change welcome to users.
    # map.connect '', :controller => "welcome" or
    # map.root :controller => "welcome"
  • Delete index.html under public node which is used to show default welcome page. Rails first look to this file then look to routes.rb to figure out what page to display.
  • In the Projects window, right-click the sampleapplication node and click to Run or you can run project from command prompt by following command under project:
    ruby script\server

Project creation has been completed and you can browse it in http://127.0.0.1:3000
Now you can create, edit, show and delete user by clicking respective link.

Validating inputs:
If you want to ensure users must provide values for both name and email fields, add following lines to User class under app/model folder of your project:
class User < ActiveRecord::Base
  validates_presence_of     :name, :email
  validates_format_of       :email, :with => /^([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})$/, :message => "Invalid"
end

Now system will give error message if you try to create user without name and email.

OK, Finally we have completed the sample application with data validation. To continue development using Ruby on Rails and skills up you will get lots of resources in web.

Click here for some good resources for Web development in Ruby on Rails

Saturday, October 4, 2008

Developing Web Application using Ruby on Rails

Rails uses the MVC pattern to organize application programming. Its provides scaffolding which can automatically construct some of the models and views for website and intended to emphasize Convention over Configuration, and the rapid development principle(DRY) and it has various packages, namely ActiveRecord(for database access), ActiveResource(web service), ActionPack, ActiveSupport and ActionMailer.

Developer can make plugins to extend existing packages. It is highly time consuming portion for a developer is the writing of reusable packages of codes that are often called during the main application – frame works.

It’s built in web server WEBrick by default, but they do use Apache or Lighttpd. Has excellent potentiality in loading the extension libraries dynamically with less maintenance. Ruby creates an environment that makes the programmers to work more clearly, faster and be more meticulous and highly imaginative.

Below are the steps to install Ruby on Rails on Windows:
  • Download ruby from ruby site or click here to download the ruby installation package.
  • Run the executable file with default setting unless you have specific needs.
  • Open command prompt and run following command:
    gem install rails --include-dependencies
    It will take some times to install all dependencies. Make sure that you are connected to internet.
  • Download the latest MySql and install with detailed configuration.
  • Run following command to update ruby gem:
    gem update --system
Congratulation! The Ruby on Rails development environment setup has been completed. Now you can start developing web application using Ruby on Rails.

You can see my another blog where I explain how you can create a sample application using Ruby on Rails.

Friday, September 12, 2008

Implementation of CruiseControl.rb and RCov

CruiseControl.rb is Ruby based continuous integration tool which is used for continuous build process including testing, email notification. Also provide the details of all build.

On the other hand, RCov is very well known code coverage tool for Ruby. It is used to get the information of test coverage.

These two tools are so good together and their implementation is incredibly simple which is describe below:

Download: Click here to download. After completing the download unpack it.

Add project: Go to the unpacked directory from command prompt and execute following command:
cruise add <project-name> --url <project-url>.
This will create a directory under cruise data, then checks out your project to ./cruise/projects/<project name>/work/

Start Cruise: Execute command: cruise start. It will run your CrouiseControl on port 3333. Browse - http://localhost:3333/. If everything is going well, you will see the the CruiseControl dashboard with project list. You can build your project and see the build report.

Create database: You have to create test database and edit database.yml to connect with database, performing rake RAILS_ENV=test db:migrate, running rake test and making sure that it passes.

Install rails_rcov: Install RCov gem to CruiseControl server by using gem install RCov and plugin to project folder by using following command:
 ruby script/plugin install http://svn.codahale.com/rails_rcov
Add rake task: If you installed the plugin into your project you have some useful rake tasks. Now you have to add “cruise.rake” task to the “lib/tasks” directory of your Ruby on Rails project with following:
desc 'Continuous build target'
task :cruise do
out = ENV['CC_BUILD_ARTIFACTS']
mkdir_p out unless File.directory? out if out

ENV['SHOW_ONLY'] = 'models,lib,helpers'
Rake::Task["test:units:rcov"].invoke
mv 'coverage/units', "#{out}/unit test coverage" if out

ENV['SHOW_ONLY'] = 'controllers'
Rake::Task["test:functionals:rcov"].invoke
mv 'coverage/functionals',"#{out}/functional test coverage" if out

Rake::Task["test:integration"].invoke
end
That’s all, now your project has code coverage. You can browse the source within the browser from dashboard and see which lines are covered and which are not. Enjoy!!

Update:
It was written on September 2008. Please click here to read documentation by thoughtworks.com

Thursday, September 11, 2008

Liquid design : Importance and Considerations

The term "liquid" implies that a Website should flow smoothly into whatever space it is given. If you use a high resolution monitor, this may mean that you need to re-size your browser a little, which most people in that situation do. If you have a low resolution monitor, you will still see the information, it will just be a little more compact.

If you do Liquid Design right, you should be able to make your pages display on almost anything and still make sense to the user.

Not everyone has perfect vision, and many of your potential customers may indeed be blind. If you build your site using relative font units and percentage based widths for common elements, you'll already be making life a lot easier for a portion of your visitors. Maybe even many of them.


Importance of 'liquid design' in creating web design
The goal of liquid design is providing similar experience to people and eliminate possible irritating design flaws such as too much white space, disappearance of certain sectors of information due to lack of space etc.

Resolution statistics and interpretation
A web designer's task is to predict the available space the web site can use to display. One must consider first of all what the web site's target audience is. For example, people who work with computers every day (programmers, other designers etc) often like to have a "bigger picture" of things hence they are more likely to have high resolutions - 1024x768 or even higher. People who access the Internet from universities or educational institutes are likely to use older computers and may use 480x640 or 600x800 resolutions.

Recent statistics show that most people use 1024x768 resolutions (nearly 44%) and 600x800 resolutions (50%). Until recently, the number of those who used 1024x768 resolutions was much lower, while 480x640 resolution was the preferred resolution by users. As technology evolves, the percentages change. Nowadays, web designers have started designing for the 600x800 and above.

The effective screen space is smaller than the actual number of pixels (e.g. width of 800 pixels and height of 600 pixels for 600x800 resolutions). The reason is that people use up space by adding toolbars and different additional buttons to their browser window. For example, when designing for a 600x800 resolution the web designer should in fact design for 409x741 (width of 741 pixels and height of 409 pixels) although this is not fail-proof for every situation.

The secret of liquid layouts
  • work out a basic layout grid before you begin coding
  • include gutters so that your columns will not spread too wide
  • use percentage units for widths of all containers and gutters
  • do not define containers that use the full width of a page - allow for browser rendering issues (such as percentage rounding)

Liquid Design: Can it be Done?
Yes, without a doubt! Fixed layouts are slowly becoming a thing of the past. And the principles and considerations involved in creating a liquid layout (rather than a fixed layout) are very easy to implement on your site.

However, the whole liquid idea does require a shift of focus. Stop thinking of the Web as a medium you can control, stop thinking for your users, and you'll be happier, your visitors will be happier, and the Web will be just a little more pleasant for everyone.

Is liquid design adequate for any web site?
In order to make a decision whether liquid design is suitable for a web site, factors such as type of content, structure, amount of information must be taken in consideration. Liquid design is ideal for sites with a lot of information. The elasticity of such sites increases readability.

Pros and Cons of Liquid design..
Pros: The major benefit of a liquid design is that the layout will adjust to fill a variety of resolutions. You can create a site that will work well at both low and high resolutions without all the empty space outside of the design. A liquid layout with it’s use of ‘em’ or percents instead of pixels will be more accessible to viewers with poor eyesight as they can more easily resize the text. It can also be easier to fit all of your content into the design for those viewers with higher resolution monitors.

Cons: A liquid design does have it’s drawbacks though .... It is time consuming. You do lose a certain amount of control over how everything will look and some of the empty space of a fixed design will work it’s way internally into the liquid design. There is also the issue of line length growing to wide which will make you text difficult to read. Using max-width is an option for browsers outside of Internet Explorer. IE will need it’s own workaround to keep your lines of text from becoming too wide. A liquid layout can often be more difficult and time consuming to develop and test.

Click here to download sample application on liquid design.

Thursday, August 21, 2008

Importance and considerations to make a user friendly web application

From my 4+ year’s professional experience I realized some important things to build user friendly website. Actually this will help to increase users of your website. These things are not big deal. Users first want a stable and easy application which is easy to use. After this they compare features with another application.
Always assume that a web user have a short attention spans. Remember that the user will use your site is interested in your contents, not the capabilities of design software. They will think usability in place of your internal architecture. So before building any web application, you need to consider who will access your site and how they use the features.
I don’t think start-ups usually realize that it’s not only important to have a functioning site, but a functional site as well.
Check for errors regularly:
Every stable/unstable web application needs to be checked at least once a month for any broken links. Also you can get help some tools to check link; such as Link Defender. Make sure that your site is stable and reliable in different browser and avoid any unnecessary downtime. Add details explanation for any failure.
Never assume that the viewers have the latest browser. If you have to include anything that will only work with the latest version, try to make sure that it is not crucial to the workings of your site
Other important things are to check spelling or grammatical mistakes. If needed, you can consult with trusted ones who can help you in this regards.
Site working properly:
This is the main thing for any application. Ensure that all things are working well which you provided. If any feature is not working well then you should not provide that feature.
Consistent design layout:
It is the most important thing for a web application. Try to keep your site consistent. Don't use too many fonts, especially special fonts that may not be available on the computer of the person viewing your site. Make sure to use a consistent design and layout for each page on your site. Ensure the same general text color scheme, logo, consistent navigation menu, button, list style, entry form and header and footer in the
same place with consistent attributes. You should use template based design which will help u to create consistent design.
Navigation structure:
Display meaningful navigation menus, logical headings, link descriptions and logical breadcrumbs (e.g. Home ? Products ? HDD) which will help users to know current browsing place and guide visitors. Add easy and meaningful links for next task and add help texts if needed. Use a text-based navigation menu instead of a graphical or drop-down JavaScript menu.
Site map:
You should include a text and image based site map with a link of every page, and add short details of every page. If you use good site map then you don’t have to add links to every page from your home page. Many sites use site maps, but does not update regularly and keep these well descriptive to find pages.
Search tools and search engine:
To build intuitive applications you need to provide search facility in the site. It will be helpful for users.
Ensure that your site is search engine compatible. If possible use texts in place of graphics. Avoid frames, flash and graphical text. Use logical title and META tags for each page and include meaningful keywords to META tag.
Other things:
To build an intuitive web application you should consider following things too:
  • Include contact details. If you don’t provide the way to contact, then people will hesitate to trust you.
  • Add feedback form so that anyone can give feedback which will help to build excellent application.
  • Use simple language to understand which is helpful for all type of user’s (regional users). Minimize texts as far as possible. You need to prioritize user’s interest most.
  • Make user friendly URLs. A user friendly URL must be short, lowercase, plain language and conventional. URLs are often the single barrier that prevents millions of users from visiting a site.
  • Always try to minimize fancy stuffs.
  • Remove unnecessary image which will help to load your page quickly.

Friday, June 13, 2008

Extract href links from a website content using regular expression

One of my previous post I have discussed about to Grab website content using cURL. In this post I have given a sample code snippet to extract all hyper links from grabbed content using regular expression.

By using following class you can grab site content and extract all hyper links:
class ScrapWebsite
{
    var $target_url = '';
    var $content = '';
    var $base_url = '';
    var $href_links = array();

    function __construct($url)
    {
        $this->target_url = $url;
        $this->getBaseUrl();
    }

    function extractHtml()
    {
        $options = array(
            CURLOPT_RETURNTRANSFER => true, // return web page
            CURLOPT_HEADER => false, // don't return headers
            CURLOPT_FOLLOWLOCATION => true, // follow redirects
            CURLOPT_ENCODING => "", // handle all encodings
            CURLOPT_USERAGENT => "spider", // who am i
            CURLOPT_AUTOREFERER => true, // set referer on redirect
            CURLOPT_CONNECTTIMEOUT => 120, // timeout on connect
            CURLOPT_TIMEOUT => 120, // timeout on response
            CURLOPT_MAXREDIRS => 10, // stop after 10 redirects
            CURLOPT_SSL_VERIFYPEER => false,
            CURLOPT_SSL_VERIFYHOST => false
        );

        $ch = curl_init($this->target_url);
        curl_setopt_array($ch, $options);
        $this->content = curl_exec($ch);

        curl_close($ch);
    }

    function getBaseUrl()
    {
        $this->base_url = parse_url($this->target_url, PHP_URL_HOST);
        $this->base_url = 'http://' . $this->base_url;
    }

    function extractHref()
    {
        preg_match_all('/\]*href\s*=\s*\"([^\"]*)\"[^>]*>(.*?)<\/a>/', 
        $this->content, $matches);

        for ($i = 0; $i < count($matches[1]); $i++) {
            if (!(preg_match('/\<|#/', $matches[2][$i], $match)
                || preg_match('/javascript:void/', $matches[1][$i], $match))
            ) {
                if (preg_match('/www\.|http:/', $matches[1][$i], $um))
                    $url = $matches[1][$i];
                else
                    $url = $this->base_url . $matches[1][$i];

                $title = trim($matches[2][$i]) ? $matches[2][$i] : $url;

                $this->href_links[] = array($url, $title);
            }
        }
    }
}
//Junk code  generated by syntax highlighter :)

Uses
$scrap = new ScrapWebsite('http://www.scripts.morshed-alam.com');
$scrap->extractHtml();
$scrap->extractHref();
The above code create a instance of scrap class, grab content and extract all links in to class variable $href_links to use further. Note: Use input url validation to avoid exception.

Click here to see the demo

Friday, May 23, 2008

Grab website content using cURL

A website content can grab easily using cURL by following the steps below:
  • Enable cURL
  • Copy following codes in to PHP file
  • Change target URL
  • Run the page from webserver
$target_url = "http://www.morshed-alam.com";

$options = array(
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_HEADER => false,
    CURLOPT_FOLLOWLOCATION => true,
    CURLOPT_ENCODING => "",
    CURLOPT_USERAGENT => "spider",
    CURLOPT_AUTOREFERER => true,
    CURLOPT_CONNECTTIMEOUT => 120,
    CURLOPT_TIMEOUT => 120,
    CURLOPT_MAXREDIRS => 10,
    CURLOPT_SSL_VERIFYPEER => false,
    CURLOPT_SSL_VERIFYHOST => false,
    CURLOPT_URL => $target_url
);

$ch = curl_init($url);

curl_setopt_array($ch, $options);

$content = curl_exec($ch);

curl_close($ch);
Click here to see the cURL Manual
Extract href links from a website link
Demo page to show extracted href links from a website

Friday, April 25, 2008

Memory overflow issue

I am writing this one to share my experience to you. In the very beginning of my professional career, I have developed an web application for Shylhet Chamber of Commerce using LAMP and delivered it successfully. Almost three months(Couldn't remind exactly) later we have notified from client that they couldn't log into the application. Then i had gone there and investigate the problem. First I was very confused because..
  • System not given any types of error message while trying to log-in.
  • There is no error message in logger
  • There is no problem in code
  • Even though, tried to run a sample script in server but I didn't
Think about that, What was the condition that time!!!

Then tried to narrow down the error scope by checking PHP, Apache, Mysql settings and check the application storage and got that "There is no space in document root." which was the culprit for this problem. Even though application couldn't flash a single message because there was no space to show a message.

That's it. So, I think anyone should keep it in mind about storage.