Easy lessons for Ruby on Rails newbies
As a newbie, getting started with Rails was tricky without some help from the
IRC folks. If you get stuck, that’s a good place for help, as the author hangs out in there pretty regularly.
That said, some sample code is worth its weight in gold, so here’s how I got a basic Rails application running.
First, check GettingStartedWithRails for some gotchas, and then read http://api.rubyonrails.org/ for some installation tips. I will repeat some of it here, but that is where I started.
Requirements
You can skip a lot of installation problems on Windows by simply using InstantRails
- Apache 1.3.x or 2.x (or any FastCGI?-capable webserver with a mod_rewrite-like module)
- FastCGI? (or mod_ruby) for production performance (CGI is used for development)
- Database and driver (e.g. MySQL, PostgreSQL, or SQLite)
Optional
You can use a IDE to program with Rails.
Get RadRails at http://www.radrails.org
Getting started
1a. Set up Apache for the Rails application (see “Apache configuration example” below1.)
or
1b. Run the WEBrick servlet: ruby script/server -- help (see “WEBrick configuration example” below2.)(Run this from the Rails application directory)
2. Go to http://rails/ (or whatever your ServerName is) and check that you get the “Congratulations, you’re on Rails!” screen
2b. In case of WEBrick, go to http://localhost:3000. Apache2 note: The httpd.conf contains an entry which determines the port to be used. For example, ServerName AServerNameHere:80, port 80 was selected. Try the following url http://localhost:80/.
3. Follow the guidelines on the “Congratulations, you’ve put Ruby on Rails!” screen
Apache configuration example for Apache 2
1 In the Apache configuration below, replace ”/path/application” in each case with the full path to the rails directory unpacked with the tar.gz….
( I am not quite sure what the author means by ” full path to the rails directory unpacked with the tar.gz” In fact it is rather confusing for a ruby newby… I think he means the path that you create by executing “rails /path/to/FILENAME”).
and be sure to append the “public” or “log” directory where noted below. I also had to turn on CGI and set some access requirements – also shown below (Suse 9.1’s Apache is locked down fairly tight)
ServerName rails
DocumentRoot /path/application/public/
ErrorLog /path/application/log/apache.log
Options ExecCGI FollowSymLinks
AddHandler cgi-script .cgi
AllowOverride all
Order allow,deny
Allow from all
An alternative Apache 2 configuration example, that modifies your existing Apache to have a rails enabled directory (rather than a dedicated virtual host) might be
Alias /rails/ /var/www/rails/
Options ExecCGI
AddHandler cgi-script .cgi
AllowOverride all
Order allow,deny
Allow from all
This alternative configuration will also require
RewriteBase /rails
to be added to the application’s .htaccess file (in /path/to/application/public), where
/rails is the value supplied to the app’s Alias directive in
httpd.conf. You should now be able to access your application at:
WEBrick configuration example
2 WEBrick servlet help output
$ ruby script/server --help
Usage: ruby server [options]
-p, --port=port Runs Rails on the specified port.
Default: 3000
-b, --binding=ip Binds Rails to the specified ip.
Default: 127.0.0.1
-i, --index=controller Specifies an index controller
that requests for root will go to
(instead of congratulations screen).
-d, --daemon Make Rails run as a Daemon (only works if
fork is available -- meaning on *nix).
-c, --cache-classes Caches class compilation which will speed up
the serving of requests, but require a
server restart on source changes.
-h, --help Show this help message.
Congratulations, you’re on Rails!
You’ve successfully configured your web-server to point at this Rails application.
Once you have seen this in your web browser, your rails application is ready to begin programming. Follow these steps:
1. TutorialStepOne – Create empty production and test databases for your application.
2. TutorialStepTwo – Edit config/database.yml with your database settings.
3. TutorialStepThree – Create a new controller using the script/generate controller generator
(run with no arguments for documentation).
4. TutorialStepFour – Create a new model using the script/generate model generator
(run with no arguments for documentation).
5. TutorialStepFive – See all the tests run and the app documentation be created by running rake.
6. TutorialStepSix – Develop your Rails application!
7. Setup FastCGI? or mod_ruby to get production-level performance
Resources
Ruby on Rails Framework
, often called
RoR or just
Rails, is an
open source web application framework written in
Ruby that closely follows the
Model-View-Controller (MVC) architecture.
It strives for simplicity and allowing real-world applications to be developed in less code than other frameworks and with a minimum of configuration.
The Ruby programming language allows for extensive metaprogramming, which Rails makes much use of. This results in a very readable syntax, in the opinion of many of its users.
Rails is primarily distributed through RubyGems, which is the official packaging format and distribution channel for Ruby libraries and applications.
History
Ruby on Rails was extracted from Basecamp, a project-management tool, by 37signals. It was first released to the public in July 2004.
Rails' MVC architecture
The pieces of the Model-View-Controller (MVC) architecture in Ruby on Rails are as follows:
Model
In object-oriented, database-driven MVC web applications, Model consists of the classes representing RDBMS tables.
In Ruby on Rails, Model classes are handled through the Active Record. Usually, all the programmer needs to do is to subclass the ActiveRecord::Base class, and the program will automatically figure out which RDBMS table to use and what columns the table has.
The class definitions also specify the relations between classes with object-relational mapping commands. For example, if the class name Image has a definition has_many :comments, and there is an instance of Image named a, then a.comments will return an array with all Comment objects with image_id equal to a.id.
The data validation handlers (e.g. validates_uniqueness_of :checksum) and any update-related handlers (e.g. after_destroy :remove_file, before_update :update_related_details) are also specified and implemented in the model class.
View
In MVC, View is the display logic, or how the data from the Controller classes is displayed. In web applications, this frequently consists of a minimal amount of code, interspersed in HTML.
There are currently many ways the views can be handled – the underlying view code is part of the Action Pack. The method in Rails itself is to use Embedded Ruby (.rhtml files), which are basically fragments of HTML with some Ruby code interspersed, with syntax quite similar to JSP. HTML and XML can also be constructed programmatically with Builder or through Liquid template system.
For each method in the controller that needs to display user output, a small HTML code fragment needs to be written. The page layout is described separately from the controller action that displays layouts, and the fragments can also call other fragments.
Controller
In MVC, Controller classes respond to user interaction and call the application logic, which in turn manipulates the data in Model and displays the data through View. In web-based MVC applications, the Controller methods are initiated by the user through the web browser.
Controller implementation is handled through Rails' Action Pack, which contains the class ApplicationController. Rails applications simply subclass ApplicationController and write required actions as methods, which can then be accessed through the web, typically in form of /example/method, which calls ExampleController#method, and presents the data using the view file /app/views/example/method.rhtml, unless the method redirects elsewhere.
Rails also provides out-of-the-box scaffolding, which can quickly construct most of the logic and views needed to do common operations, such as CRUD.
Other modules
In addition to this, Rails also offers some other modules, like Action Mailer for sending email and Action Web Service for SOAP and XML-RPC support.
Ajax on Rails
A separate technology called Ajax, which allows for using JavaScript and XML to process queries by a web browser to a webserver as background processing without loading additional webpages, has been combined with this technology to produce a system referred to as "Ajax on Rails." Rails provides several helpers that make implementing Ajax applications easier.
Rails is host to both the Prototype JavaScript framework, a toolkit providing for Ajax calls and other functionality for often occurring client-side programming tasks, and script.aculo.us, a JavaScript library for user interface enhancement (advanced form controls, visual effects, drag and drop).
Web server support
For development and testing, the lightweight WEBrick web server included with Ruby is often used as the application server. For production use, Apache or Lighttpd with FastCGI is recommended, but any web server with CGI or FastCGI support will work. On Apache, mod_ruby can help with performance considerably, though its use is frequently discouraged because it is unsafe to share multiple RoR applications on Apache. [1]
Database support
Since the Rails architecture strongly favors database use, an RDBMS system is recommended for data storage, but Rails also supports the SQLite library if running an RDBMS server is not possible. The database access is entirely abstracted from programmer's point of view, and Rails handles access to all databases automatically – though, if needed, using direct SQL queries is possible. Rails attempts to maintain database-neutrality, application portability over different database systems, and usability of pre-existing databases for Rails application development as much as possible, though due to different feature sets of the RDBMSes, it is not completely guaranteed by the framework alone. Several different RDBMS systems are supported, including MySQL, PostgreSQL, SQLite, IBM DB2, Oracle and Microsoft SQL Server.
Projects Using Ruby on Rails
Major software projects written using Ruby on Rails include:
Some major websites and services that are implemented on top of Ruby on Rails include:
Requirements
- Web server such as Apache 1.3.x or 2.x, lighttpd, or any FastCGI-capable webserver with a mod_rewrite-like module. For development, Rails' "server" script uses WEBrick, which may be used in place of other web servers. However, WEBrick generally exhibits slow performance and is not recommended for production use.
- FastCGI for production performance. CGI is possible but quite slow. Rails supports Apache's mod_ruby.
- Database and driver (e.g. MySQL, PostgreSQL, or SQLite)
See also
External links
What's Ruby?
Ruby is the interpreted scripting language for quick and easy object-oriented programming. It has many features to process text files and to do system management tasks (as in Perl). It is simple, straight-forward, extensible, and portable.
Oh, I need to mention, it's totally free, which means not only free of charge, but also freedom to use, copy, modify, and distribute it.
Features of Ruby
- Ruby has simple syntax, partially inspired by Eiffel and Ada.
- Ruby has exception handling features, like Java or Python, to make it easy to handle errors.
- Ruby's operators are syntax sugar for the methods. You can redefine them easily.
- Ruby is a complete, full, pure object oriented language: OOL. This means all data in Ruby is an object, in the sense of Smalltalk: no exceptions. Example: In Ruby, the number 1 is an instance of class Fixnum.
- Ruby's OO is carefully designed to be both complete and open for improvements. Example: Ruby has the ability to add methods to a class, or even to an instance during runtime. So, if needed, an instance of one class *can* behave differently from other instances of the same class.
- Ruby features single inheritance only, *on purpose*. But Ruby knows the concept of modules (called Categories in Objective-C). Modules are collections of methods. Every class can import a module and so gets all its methods for free. Some of us think that this is a much clearer way than multiple inheritance, which is complex, and not used very often compared with single inheritance (don't count C++ here, as it has often no other choice due to strong type checking!).
- Ruby features true closures. Not just unnamed function, but with present variable bindings.
- Ruby features blocks in its syntax (code surrounded by '{' ... '}' or 'do' ... 'end'). These blocks can be passed to methods, or converted into closures.
- Ruby features a true mark-and-sweep garbage collector. It works with all Ruby objects. You don't have to care about maintaining reference counts in extension libraries. This is better for your health. ;-)
- Writing C extensions in Ruby is easier than in Perl or Python, due partly to the garbage collector, and partly to the fine extension API. SWIG interface is also available.
- Integers in Ruby can (and should) be used without counting their internal representation. There *are* small integers (instances of class Fixnum) and large integers (Bignum), but you need not worry over which one is used currently. If a value is small enough, an integer is a Fixnum, otherwise it is a Bignum. Conversion occurs automatically.
- Ruby needs no variable declarations. It uses simple naming conventions to denote the scope of variables. Examples: simple 'var' = local variable, '@var' = instance variable, '$var' = global variable. So it is also not necessary to use a tiresome 'self.' prepended to every instance member.
- 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 Linux, but works on many types of UNIX, DOS, Windows 95/98/Me/NT/2000/XP, MacOS, BeOS, OS/2, etc.
The Creator of Ruby
Yukihiro Matsumoto, a.k.a Matz matz@netlab.jp