Showing posts with label Ruby. Show all posts
Showing posts with label Ruby. Show all posts

Rail Frame work

0 comments

A framework is a program, set of programs, and/or code library that writes most of your application for you. When you use a framework, your job is to write the parts of the application that make it do the specific things you want.

When you set out to write a Rails application, leaving aside configuration and other housekeeping chores you have to perform three primary tasks:

  • Describe and model your application's domain: The domain is the universe of your application. The domain may be music store, university, dating service, address book, or hardware inventory. So here you to figure out what's in it, what entities exist in this universe and how the items in it relate to each other. This is equivalent to modeling database structure to keep the entities and their relationship.

  • Specify what can happen in this domain: The domain model is static, Now you have to get dynamic. Addresses can be added to an address book. Musical scores can be purchased from music stores. Users can log in to a dating service. Students can register for classes at a university. You need to identify all the possible scenarios or actions that the elements of your domain can participate in.

  • Choose and design the publicly available views of the domain: At this point, you can start thinking in Web-browser terms. Once you've decided that your domain has students, and that they can register for classes, you can envision a welcome page, a registration page, and a confirmation page etc.Each of these pages, or views, shows the user how things stand at certain point.

Based on the above three tasks, Ruby on Rails deals with a Model/View/Controller (MVC) framework.

Ruby on Rails MVC framework:

The Model View Controller principle divides the work of an application into three separate but closely cooperative subsystems.

Model (ActiveRecord ) :

Maintains the relationship between Object and Database and handles validation, association, transactions, and more.

This subsystem is implemented in ActiveRecord library which provides an interface and binding between the tables in a relational database and the Ruby program code that manipulates database records. Ruby method names are automatically generated from the field names of database tables, and so on.

View ( ActionView )

A presentation of data in a particular format, triggered by a controller's decision to present the data. They are script based templating systems like JSP, ASP, PHP and very easy to integrate with AJAX technology.

This subsystem is implemented in ActionView library which is an Embedded Ruby (ERb) based system for defining presentation templates for data presentation. Every Web connection to a Rails application results in the displaying of a view.

Controller ( ActionController ):

The facility within the application that directs traffic, on the one hand querying the models for specific data, and on the other hand organizing that data (searching, sorting, massaging it) into a form that fits the needs of a given view.

This subsystem is implemented in ActionController which is a data broker sitting between ActiveRecord (the database interface) and ActionView (the presentation engine).

Pictorial Representation of MVC Framework:

A Pictorial Diagram of Ruby on Rails Framework is given here:

Rails Framework

Directory Representation of MVC Framework:

Assuming a standard, default installation over Linux, you can find them like this:

tp> cd /usr/local/lib/ruby/gems/1.8/gems
tp> ls

You will see subdirectories including (but not limited to) the following:

  • actionpack-x.y.z
  • activerecord-x.y.z
  • rails-x.y.z

Over a windows installation you can find them link this:

C:\>cd ruby\lib\ruby\gems\1.8\gems
C:\ruby\lib\ruby\gems\1.8\gems\>dir

You will see subdirectories including (but not limited to) the following:

  • actionpack-x.y.z
  • activerecord-x.y.z
  • rails-x.y.z

ActionView and ActionController are bundled together under ActionPack.

ActiveRecord provides a range of programming techniques and shortcuts for manipulating data from an SQL database. ActionController and ActionView provide facilities for manipulating and displaying that data. Rails ties it all together.

Ruby on Rails Directory Structure


When you use the rails helper script to create your application, it creates the entire directory structure for the application. Rails knows where to find things it needs within this structure, so you don't have to tell it.

Here is a top level view of directory tree created by helper script at the time of application creation. Except for minor changes between releases, every Rails project will have the same structure, with the same naming conventions. This consistency gives you a tremendous advantage; you can quickly move between Rails projects without relearning the project's organization.

To understand this directory structure let's use demo application created in installation chapter. This can be created using a simple helper command C:\ruby\> rails demo.

Now go into demo application root directory as follows:

C:\ruby\> cd demo
C:\ruby\demo> dir

You will find a directory structure as follows:

demo/
..../app
......../controller
......../helpers
......../models
......../views
............../layouts
..../components
..../config
..../db
..../doc
..../lib
..../log
..../public
..../script
..../test
..../tmp
..../vendor
README
Rakefile

Now let's explain the purpose of each directory

  • app : This organizes your application components. It's got subdirectories that hold the view (views and helpers), controller (controllers), and the backend business logic (models).

  • app/controllers: The controllers subdirectory is where Rails looks to find controller classes. A controller handles a web request from the user.

  • app/helpers: The helpers subdirectory holds any helper classes used to assist the model, view, and controller classes. This helps to keep the model, view, and controller code small, focused, and uncluttered.

  • app/models: The models subdirectory holds the classes that model and wrap the data stored in our application's database. In most frameworks, this part of the application can grow pretty messy, tedious, verbose, and error-prone. Rails makes it dead simple!

  • app/view: The views subdirectory holds the display templates to fill in with data from our application, convert to HTML, and return to the user's browser.

  • app/view/layouts: Holds the template files for layouts to be used with views. This models the common header/footer method of wrapping views. In your views, define a layout using the layout :default and create a file named default.rhtml. Inside default.rhtml, call <% yield %> to render the view using this layout.

  • components : This directory holds components tiny self-contained applications that bundle model, view, and controller.

  • config: This directory contains the small amount of configuration code that your application will need, including your database configuration (in database.yml), your Rails environment structure (environment.rb), and routing of incoming web requests (routes.rb). You can also tailor the behavior of the three Rails environments for test, development, and deployment with files found in the environments directory.

  • db: Usually, your Rails application will have model objects that access relational database tables. You can manage the relational database with scripts you create and place in this directory.

  • doc: Ruby has a framework, called RubyDoc, that can automatically generate documentation for code you create. You can assist RubyDoc with comments in your code. This directory holds all theR ubyDoc-generated Rails and application documentation.

  • lib: You'll put libraries here, unless they explicitly belong elsewhere (such as vendor libraries).

  • log: Error logs go here. Rails creates scripts that help you manage various error logs. You'll find separate logs for the server (server.log) and each Rails environment (development.log, test.log, and production.log).

  • public: Like the public directory for a web server, this directory has web files that don't change, such a s JavaScript files (public/javascripts), graphics (public/images), stylesheets (public/stylesheets), and HTML files (public).

  • script: This directory holds scripts to launch and manage the various tools that you'll use with Rails. For example, there are scripts to generate code (generate) and launch the web server (server).

  • test: The tests you write and those Rails creates for you all go here. You'll see a subdirectory for mocks (mocks), unit tests (unit), fixtures (fixtures), and functional tests (functional).

  • tmp: Rails uses this directory to hold temporary files for intermediate processing.

  • vendor: Libraries provided by third-party vendors (such as security libraries or database utilities beyond the basic Rails distribution) go here.

Apart from these directories there will be two files available in demo directory.

  • README: This file contains a basic detail about Rail Application and description of the directory structure explained above.

  • Rakefile: This file is similar to Unix Makefile which helps with building, packaging and testing the Rails code. This will be used by rake utility supplied along with Ruby installation.


Ruby on Rails Examples


Subsequent chapters are based on the example given in this chapter. In this example we will create something simple but operational online library system for holding and managing the books.

Now you have to be patient till you go through next few chapters. I'm sure after completing this tutorial you will have complete understanding on Rails.

This application has a basic architecture and will be built using two ActiveRecord models to describe the types of data that is stored:

  • Books, which describes an actual listing.

  • Subject, which is used to group books together.

Workflow for creating Rails applications:

A recommended workflow for creating Rails Application is as follows:

  • Use the rails command to create the basic skeleton of the application.

  • Create a database on the MySQL server to hold your data.

  • Configure the application to know where your database is located and the login credentials for it.

  • Create Rails Active Records ( Models ) because they are the business objects you'll be working with in your controllers.

  • Generate Migrations that makes creating and maintaining database tables and columns easy.

  • Write Controller Code to put a life in your application.

  • Create Views to present your data through User Interface.

So lets start with creating our library application.

Creating an Empty Rails Web Application:

Rails is both a runtime web application framework and a set of helper scripts that automate many of the things you do when developing a web application. In this step, we will use one such helper script to create the entire directory structure and the initial set of files to start our Library System application.

  1. Go into ruby installation directory to create your application.
  2. Run the following command to create a skeleton for library application.
C:\ruby> rails library

This will create a subdirectory for the library application containing a complete directory tree of folders and files for an empty Rails application. Check a complete directory structure of the application. Check Rails Directory Structure for more detail.

Most of our development work will be creating and editing files in the library/app subdirectories. Here's a quick rundown of how to use them:

  • The controllers subdirectory is where Rails looks to find controller classes. A controller handles a web request from the user.

  • The views subdirectory holds the display templates to fill in with data from our application, convert to HTML, and return to the user's browser.

  • The models subdirectory holds the classes that model and wrap the data stored in our application's database. In most frameworks, this part of the application can grow pretty messy, tedious, verbose, and error-prone. Rails makes it dead simple.

  • The helpers subdirectory holds any helper classes used to assist the model, view, and controller classes. This helps to keep the model, view, and controller code small, focused, and uncluttered.

Starting Web Server:

Rails web application can run under virtually any web server, but the most convenient way to develop a Rails web application is to use the built-in WEBrick web server. Let's start this web server and then browse to our empty library application:

This server will be started from the application directory as follows. This runs on port number 3000.

C:\> cd ruby\library 
C:\ruby\library\> ruby script/server

This will start your WEBrick web server.

Now open your browser and browse to http://127.0.0.1:3000. If everything is gone fine then you should see a greeting message from WEBrick otherwise there is something wrong with your setting.

What is next ?

Next session will teach you how to create databases for your application and what is the configuration required to access these created databases.

Further we will see what is Rail Migration and how it is used to maintain database tables.



Download Ruby

0 comments




Ruby Source Code

Installing from the source code is a great solution for when you are comfortable enough with your platform and perhaps need specific settings for your environment. It’s also a good solution in the event that there are no other premade packages for your platform.

  • Ruby 1.9.1-p129 (md5: c71f413514ee6341c627be2957023a5c) Stable Version (recommended)
  • Stable Snapshot This is tar’ed and gzip’ed file of the latest stable SVN. It should be better than the last stable release.
  • Nightly Snapshot This is tar’ed and gzip’ed file of the latest SVN. It may contain unfixed problems.

For information about the Ruby Subversion repository, see our Ruby Core page.

Ruby on Windows

The Windows platform has several options for installing Ruby. The first option is simply installing the compiled binaries. The second option is to use the one-click installer. If you’re unsure about how to install Ruby, the one-click installer may be the best option for you. (In addition to Ruby, the one-click installer also comes with a bunch of additional libraries built in.)

Ruby On Linux

Depending on the distribution you are using, there are several ways to install Ruby. The first option is simply to download the source code above and compile by hand. However, on some platforms, there are package management solutions that make installing Ruby extremely easy.

For example, on Debian or Ubuntu apt-get provides an easy and elegant solution:

% sudo apt-get install ruby irb rdoc

For irb and rdoc you will need to enable the universe repository.

Ruby On OS X

Ruby 1.8.6 is fully supported in Mac OS X Leopard including Ruby on Rails, Mongrel, Capistrano, and many other popular Ruby gems (packages). For details, see the Ruby wiki at MacOS Forge.

Mac OS X Tiger is packaged with version 1.8.2 of Ruby, but, for those who haven’t upgraded to Leopard, there are a number of options for installing the latest version of Ruby. Locomotive is a nice choice if you are looking for something to get you up and running quickly for Rails development. Using MacPorts or Fink might be a little nicer for the more technically savvy.

On MacPorts, you can install Ruby with…

% port install ruby

Fink has a graphical interface (using Fink Commander) for installing Ruby.

Also, since OS X is based on Unix, downloading and installing from the source is just as easy and effective as the other solutions.

For a detailed look at installing Ruby (and Rails), Dan Benjamin’s excellent articles for Tiger and for Leopard will get you up and running very quickly.

Ruby On Solaris and OpenSolaris

Ruby 1.8.7 is available for Solaris 8 through Solaris 10 on Sunfreeware and Ruby 1.8.6 is available at Blastwave. An optimized Ruby on Rails stack for Solaris 10 is available as Coolstack from Sun’s Cooltools project.

To install Ruby on OpenSolaris, please use the Image Packaging System, or IPS client. This will install the latest Ruby binaries and Rubygems directly from the OpenSolaris network repository. It’s easy:

% pfexec pkg install SUNWruby18

This will install Ruby, Rubygems, common extensions and their supporting libraries. This package also contains DTrace support and performance optimizations. The locations of various artifacts are described in the Ruby OpenSolaris ARC Case.

The other OpenSolaris distribution, called the Solaris Express Community Edition or SXCE comes with Ruby preinstalled. The version, location etc., are the same as with the vanilla OpenSolaris distribution, and are documented in the above mentioned ARC case.

To install SVR4 packages manually, please visit the RubyOpenSolaris project @ Rubyforge.

Ruby-The Red Diamond of Programming Languages

0 comments

Ruby is a language of careful balance. Its creator, Yukihiro “matz” Matsumoto, blended parts of his favorite languages (Perl, Smalltalk, Eiffel, Ada, and Lisp) to form a new language that balanced functional programming with imperative programming.

He has often said that he is “trying to make Ruby natural, not simple,” in a way that mirrors life.Building on this, he adds:
Ruby is simple in appearance, but is very complex inside, just like our human body1.

About Ruby’s Growth

Since its public release in 1995, Ruby has drawn devoted coders worldwide. In 2006, Ruby achieved mass acceptance. With active user groups formed in the world’s major cities and Ruby-related conferences filled to capacity.


The TIOBE index, which measures the growth of programming languages, ranks Ruby as #9 among programming languages worldwide. Much of the growth is attributed to the popularity of software written in Ruby, particularly the Ruby on Rails web framework2.

Ruby is also totally free. Not only free of charge, but also free to use, copy, modify, and distribute.


Seeing Everything as an Object

Initially, Matz looked at other languages to find an ideal syntax. Recalling his search, he said, “I wanted a scripting language that was more powerful than Perl, and more object-oriented than Python3.”

In Ruby, everything is an object. Every bit of information and code can be given their own properties and actions. Object-oriented programming calls properties by the name instance variables and actions are known as methods. Ruby’s pure object-oriented approach is most commonly demonstrated by a bit of code which applies an action to a number.

5.times { print "We *love* Ruby -- it's outrageous!" }

In many languages, numbers and other primitive types are not objects. Ruby follows the influence of the Smalltalk language by giving methods and instance variables to all of its types. This eases one’s use of Ruby, since rules applying to objects apply to all of Ruby.

Ruby’s Flexibility

Ruby is seen as a flexible language, since it allows its users to freely alter its parts. Essential parts of Ruby can be removed or redefined, at will. Existing parts can be added upon. Ruby tries not to restrict the coder.

For example, addition is performed with the plus (+) operator. But, if you’d rather use the readable word plus, you could add such a method to Ruby’s builtin Numeric class.

class Numeric
def plus(x)
self.+(x)
end
end

y = 5.plus 6
# y is now equal to 11

Ruby’s operators are syntactic sugar for methods. You can redefine them as well.
Blocks, a Truly Expressive Feature

Ruby’s block are also seen as a source of great flexibility. A programmer can attach a closure to any method, describing how that method should act. The closure is called a block and has become one of the most popular features for newcomers to Ruby from other imperative languages like PHP or Visual Basic.

Blocks are inspired by functional languages. Matz said, “in Ruby closures, I wanted to respect the Lisp culture4.”

search_engines =
%w[Google Yahoo MSN].map do |engine|
"http://www." + engine.downcase + ".com"
end

In the above code, the block is described inside the do ... end construct. The map method applies the block to the provided list of words. Many other methods in Ruby leave a hole open for a coder to write their own block to fill in the details of what that method should do.
Ruby and the Mixin

Unlike many object-oriented languages, Ruby features single inheritance only, on purpose. But Ruby knows the concept of modules (called Categories in Objective-C). Modules are collections of methods.

Classes can mixin a module and receive all its methods for free. For example, any class which implements the each method can mixin the Enumerable module, which adds a pile of methods that use each for looping.

class MyArray
include Enumerable
end

Generally, Rubyists see this as a much clearer way than multiple inheritance, which is complex and can be too restrictive.
Ruby’s Visual Appearance

While Ruby often uses very limited punctuation and usually prefers English keywords, some punctuation is used to decorate Ruby. Ruby needs no variable declarations. It uses simple naming conventions to denote the scope of variables.

* var could be a local variable.
* @var is an instance variable.
* $var is a global variable.

These sigils enhance readability by allowing the programmer to easily identify the roles of each variable. It also becomes unnecessary to use a tiresome self. prepended to every instance member.
Beyond the Basics

Ruby has a wealth of other features, among which are the following:

* Ruby has exception handling features, like Java or Python, to make it easy to handle errors.

* Ruby features a true mark-and-sweep garbage collector for all Ruby objects. No need to maintain reference counts in extension libraries. As Matz says, “This is better for your health.”

* Writing C extensions in Ruby is easier than in Perl or Python, with a very elegant API for calling Ruby from C. This includes calls for embedding Ruby in software, for use as a scripting language. A SWIG interface is also available.

* Ruby can load extension libraries dynamically if an OS allows.

* Ruby features OS independent threading. Thus, for all platforms on which Ruby runs, you also have multithreading, regardless of if the OS supports it or not, even on MS-DOS!

* Ruby is highly portable: it is developed mostly on GNU/Linux, but works on many types of UNIX, Mac OS X, Windows 95/98/Me/NT/2000/XP, DOS, BeOS, OS/2, etc.

Advertisement

 

Copyright 2009 All Rights Reserved SITS