Using Oracle and Ruby on Rails 

Purpose

This tutorial shows you the installation of Ruby/Rails with Oracle and shows how to develop highly efficient and functional Ruby/Rails applications. You will gain the knowledge needed to create powerful Ruby/Rails appplications for your enterprise.

Topics

This tutorial covers the following topics:

 Overview
 Prerequisites
 1. Creating a Connection
 2. Query Data
 3. Bind Variables
 4. Define Datatypes
 5. Transaction Management
 6. Use PL/SQL
 7. Use LOB: Store/Retrieve Images
 8. Use XML
 9. Use ActiveRecord
 10. Ruby On Rails (RoR): Migration and Scaffold
 11. RoR: One-To-One Relationship between tables
 12. RoR: One-To-Many Relationship between tables
 13. RoR: Many-To-Many Relationship between tables
 Summary
 Related Information
 Appendix: Ruby Primer
 Appendix: How to Modify Database Tables using Rails Migration
 Appendix: Installing Ruby on Rails with Oracle

Viewing Screenshots

 Place the cursor over this icon to load and view all the screenshots for this tutorial. (Caution: This action loads all screenshots simultaneously, so response time may be slow depending on your Internet connection.)

Note: Alternatively, you can place the cursor over an individual icon in the following steps to load and view only the screenshot associated with that step. You can hide an individual screenshot by clicking it.

Overview

Ruby on Rails is a free web application framework that aims to increase the speed and ease with which database-driven web sites can be created and offers skeleton code frameworks (scaffolding) from the outset. Often shortened to Rails, or RoR, Ruby on Rails is an open source project written in the Ruby programming language and applications using the Rails framework are developed using the Model-View-Controller design pattern.

RoR has gained significant traction among J2EE and PHP programmers. The attraction of both J2EE and PHP programmers makes a lot of sense when you look at the strengths of RoR. For one thing, it uses a strict model-view-controller architecture that any self-respecting design-patterns wonk would admire—this explains its attraction to J2EE developers. Second, it’s easy to build basic systems with Rails—which is attractive to PHP developers.

RoR provides gratifying solution for MVC. A model is more than just data; it enforces all the business rules that apply to that data. The model acts as both a gatekeeper and a data store. The view is responsiible for generating a user interface, normally based on data in the model. Although the view may present the user with various ways of inputting data, the view itself never handles incoming data. The view's work is done once the data is displayed.  Controllers receive events from the outside world (normally user input) , interact with the model, and display an appropriate view to the user.

RoR supplies ActiveRecord as an object-relational mapping (ORM) layer to connect to database and manipulate data. ActiveRecord closely follows the standard ORM model: tables map to classes, rows to objects, and columns to object attributes.

When a Rails application is created the following directories and files will be generated under the root:  app, components, config, db, doc, lib, log, public, Rakefile, README, script, test, tmp, vendor.

Ruby is a dynamic, open source programming language with a focus on simplicity and productivity. It has an elegant syntax that is natural to read and easy to write. To learn more about the Ruby language, see the Appendix: Ruby Primer.

To find out more information, you can view the Ruby on Rails OTN forum.

Back to Topic List

Prerequisites

For this Hands On Session, the following has already been installed for you

1.

Install Oracle Database XE or Oracle Database 11g.

2.

Install the Oracle Instant Client and OracleOnRails (ruby, rubygems, activesupport, activerecord,rake, ruby-oci8, etc.) Also configure the schema. See the following instructions located in the Appendix: Installing Ruby on Rails with Oracle.

3.

Download and untar the rubyrails.tar file. The file contains all the necessary files to perform this tutorial.

Back to Topic List

1. Creating a Connection

The commands you use in this section are as follows:

OCI8.new (userid, password, dbname = nil, privilege = nil):

Connect to Oracle by userid and password. dbname is the connect string of Net8. If you need DBA privilege, set privilege as :SYSDBA or :SYSOPER.

 

OCI8#logoff

Disconnect from Oracle. Uncommitted transactions will be rollbacked.

OCIError The exception class with Oracle's error code. You can get the error message by OCIError#message and error code by OCIError#code.

The first task in creating a ruby script is to create a connection to the database. Perform the following steps:

1.

From your terminal window, execute the connect.rb script by executing the following commands:

                                 
ruby connect.rb
                              

You should see the following message if the connection is successful, or an error if it was not.

 

2.

The commands that will be included in the rest of your scripts throughout this tutorial are as follows:

                                 
require 'config.rb'
           
 #create connection
 conn = OCI8.new(DB_USER, DB_PASSWORD, DB_SERVER)
 
 # operations on conn goes here
 
  
                                
#log out
 conn.logoff
                              

 

Back to Topic List

2. Query Data

The commands you use in this section are as follows:

OCI8#parse (sql)

Create a cursor, prepare to execute SQL statement and return the instance of OCI8::Cursor.

OCI8#exec (sql, *bindvars)

Execute the SQL statement. The type of return value depends on the type of SQL statement. When bindvars are specified, they are bound as bind variables before execution.

OCI8::Cursor#exec(*bindvars) Execute the SQL statement assigned with the cursor. The type of return value depends on the type of SQL statement.
OCI8::Cursor#getColNames Get the names of select-list as array. Use this method after exec.

To create a simple query, and display the results, perform the following steps.

1.

From your terminal window, execute the fetch.rb script by executing the following command:

                                 
ruby fetch.rb
                              

The output is shown in the screenshot.

 

2.

There is another way to write the same code that is more specific to ruby. From your terminal window, execute the fetch_r.rb script by executing the following command:

                                 
ruby fetch_r.rb
                              
                                 
The output is shown in the screenshot.
                              

 

Back to Topic List

3. Bind Variables

Binding variables improve code reusability, and remove the risk of SQL injection attacks. The commands you use in this section are as follows:

OCI8::Cursor#bind_param(key, val, type = nil, length = nil)

Bind variables explicitly. When key is number, it binds by position, which starts from 1. When key is string, it binds by the name of placeholder.

OCI8#exec (sql, *bindvars) or OCI8::Cursor#exec(*bindvars)

Can also bind variables via bindvars.

OCI8::Cursor#[key] Get/Set the value of the bind variable.

To use bind variables in this example, perform the following steps.

1.

From your terminal window, execute the bind.rb script by executing the following command:

                                 
ruby bind.rb
                              

The output is shown in the screenshot.

 

2.

To test the performance improvement by using bind variables, execute the bind_perf_test.rb script by executing the following command:

                                 
ruby bind_perf_test.rb
                              
                                 
The output is shown in the screenshot.
                              


 

Back to Topic List

4. Define Datatypes

The command you use in this section are as follows:

OCI8::Cursor#define(pos, type, length = nil)

Use this method within parse and exec. pos starts from 1. length is used when type is String.

You can explicitly indicate the date type of the fetched value. To define datatypes in this example, perform the following steps.

1.

From your terminal window, execute the define.rb script by executing the following command:

                                 
ruby define.rb
                              

The output is shown in the screenshot.

You can see the difference between the two blocks of output.

 

Back to Topic List

5. Transaction Management

When you manipulate data in an Oracle database (insert, update, or delete data), the changed or new data is only available within your database session until it is committed to the database. When the changed data is committed to the database, it is then available to other users and sessions. This is a database transaction.

Committing each change individually causes extra load on the server. In general you want all or none of your data committed.  Doing your own transaction control has performance and data-integrity benefits.

The commands you use in this section are as follows:

OCI8#autocommit

Get/Set the state of the autocommit mode. The default value is false (remember: not committed transactions are rollbacked when logoff). If true, the transaction is committed automatically whenever executing insert/update/delete statements.

OCI8#commit() Commit the transaction.
OCI8#rollback() Rollback the transaction.

To learn how to manage transactions, perform the following steps.

1.

From your terminal window, execute the transaction.rb script by executing the following command:

                                 
ruby transaction.rb
                              

This script updates a row using connection conn1. In Oracle, new data is only visible in the original database session until it is committed. The output is shown in the screenshot.

In this case, connection conn2 doesn’t know what happened in conn1’s not-committed transactions.

 

2.

Update the transaction.rb script and uncomment conn1.autocommit = true and save the file.

Execute the script again using the following command:

                                 
ruby transaction.rb
                              

Now conn2 knows there is something new. The output is shown in the screenshot.

 

3.

Committing each row individually causes extra load on the server. You can compare the performance difference between committing each row individually versus at the end of the transaction. To test the difference, execute the trans_perf_test.rb script using the following command:

                                 
ruby trans_perf_test.rb
                              

Notice that the second number is smaller than the first one. The output is shown in the screenshot.

 

Back to Topic List

6. Use PL/SQL

PL/SQL is Oracle's procedural language extension to SQL. PL/SQL stored procedures and functions are stored in the database, so accessing them is incredibly fast. Using PL/SQL stored procedures lets all database applications reuse logic, no matter how the application accesses the database. Many data-related operations can be performed in PL/SQL faster than extracting the data into a program (for example, Ruby) and then processing it.

The command you use in this section are as follows:

DBMS_UTILITY and DBMS_OUTPUT

Oracle stored packages. TO_CHAR is a built-in function.

To call PL/SQL procedure and functions in a Ruby script, perform the following steps.

1.

From your terminal window, execute the plsql.rb script by executing the following command:

                                 
ruby plsql.rb
                              

The output is shown in the screenshot.

 

Back to Topic List

7. Use LOB: Store/Retrieve Images

Oracle Character Large Object (CLOB) and Binary Large Object (BLOB) columns (and PL/SQL variables) can contain very large amounts (gigabytes) of characters and binary data. The command you use in this section are as follows:

OCI8::BLOB#available

Check whether BLOB is available or not. To use BLOB you need to insert EMPTY_BLOB() at first.

OCI8::BLOB#read(size = nil) Read at most size bytes from BLOB, or to the end of file if size is omitted.
OCI8::BLOB#write(string) Write the given string to BLOB.

To create a small application to load and display images to the database, perform the following steps.

1.

A PNG file is in the same folder with the script file. Create a folder called download. From your terminal window, execute the blob.rb script by executing the following command:

                                 
mkdir download
ruby blob.rb
                              

The output is shown in the screenshot.

 

Back to Topic List

8. Use XML

All editions of Oracle database contain "XML DB". This lab covers the basics of returning XML data from Oracle to Ruby. The command you use in this section are as follows:

DBMS_XMLGEN.getxml (statement)

Generate XML from relational data based on a SELECT statement. It returns CLOB.

To learn the basic XML capabilities of Oracle, perform the following steps.

1.

From your terminal window, execute the xml.rb script by executing the following command:

                                 
ruby xml.rb
                              

The output is shown in the screenshot.

 

Back to Topic List

9. Use ActiveRecord

Active Record connects business objects and database tables to create a persistable domain model where logic and data are presented in one wrapping. It's an implementation of the object-relational mapping (ORM) design pattern. To use ActiveRecord in this example, perform the following steps.

1.

From your terminal window, execute the activerecord.rb script by executing the following command:

                                 
ruby activerecord.rb
                              

The output is shown in the screenshot.

 

Back to Topic List

10. Ruby On Rails (RoR): Migration and Scaffold

In this rest of the tutorial, you will use the following terms:

Rake A Ruby program that builds other Ruby programs. In Rails, Rake is used to execute a series of tasks such as db:migrate, db:schema:dump, db:schema:load, db:test:prepare, db:test:purge. It is similar in scope and purpose to the popular Linux make tool.
Migration A developer can create, modify and delete his database objects in Ruby instead of Data Description Language (DDL).
Scaffold Provides a simple interface to your data, with ways of creating, editing, viewing and deleting entries that is reflected by your ActiveRecord class. When a Scaffold is generated, it will contain both controller files (which determines which pages the user of your application eventually goes to) and view files (which renders the page that the user of your application sees).

To use Migration and Scaffold to build a Rails application, perform the following steps.

1.

You will create a most basical Rails application named holapp. From your terminal window, execute the following commands:

                                 
rails holapp
cd holapp
gedit config/database.yml
                              

 

2.

Replace the development section in the file config/database.yml with the following content and then save and close the file.

                                 
development:
                                  
adapter: oracle database: orcl11g username: hr
password: hr


3.

You can now generate the comic model. From your terminal window, execute the following command:

                                 
ruby script/generate model comic
                              


 

4.

You want to edit the script that was generated. From your terminal window, enter the following command:

                                 
gedit db/migrate/001_create_comics.rb
                              

 

5.

Replace the self.up section with the following content and then save and close the file.

                                 
 def self.up
    create_table :comics do |t|
          t.column :name,:string
          t.column :description, :string
          t.column :price, :float
    end
  end
                              

 

6.

You can now rake the database migration to generate target tables. From your terminal window, enter the following command:

                                 
rake db:migrate
                              

 

7.

You can generate the scaffold for the comic model via the following command

                                 
ruby script/generate scaffold comic
                              

 

8.

Webrick is the HTTP server library written in Ruby that uses servlets to extend its capabilities. You can start the Webrick server using the following command:

                                 
ruby script/server
                              

 

9.

You can view the application. Open a browser window and enter the following URL:

                                 
http://localhost:3000/comics
                              

Create some records by clicking New Comic to ensure that the application works correctly.

 

Back to Topic List

11. RoR: One-To-One Relationship between tables

One-To-One relationship represents one row in table A is associated with zero or one rows in table B. To create a Rails application with One-To-One Relationship between tables, perform the following steps.

1.

Open another terminal window and executed the following commands:

                               
cd /home/oracle/Work/ruby/holapp
source /etc/bashrc
                            

 

2.

Generate the models for order and invoice. From your terminal window, execute the following command:

                                 
ruby script/generate model order
ruby script/generate model invoice
                              

 

3.

You want to edit the script that was generated. From your terminal window, enter the following command:

                                 
gedit db/migrate/002_create_orders.rb
                              

 

4.

Replace the self.up section with the following content and then save and close the file.

                                 
def self.up
                                  
create_table :orders do |t|
t.column :name, :string
t.column :description, :string
end
end

 

5.

You want to edit the script that was generated. From your terminal window, enter the following command:

                                 
gedit db/migrate/003_create_invoices.rb
                                  

 

6.

Replace the self.up section with the following content and then save and close the file.

                                 
                                   
                                     
def self.up
                                  
  
                                  
create_table :invoices do |t|
                                    
t.column :order_id, :integer
t.column :invoicetype, :string
t.column :description, :string
t.column :amount, :float
end
end

 

7.

You can now rake the database migration to generate target tables. From your terminal window, enter the following command:

                                 
rake db:migrate
                              

 

8.

You want to edit the script that was generated. From your terminal window, enter the following command:

                                 
gedit app/models/order.rb
                              

 

9.

Replace the contents of the file with the following and then save and close the file.

                                 
                                   
class Order < ActiveRecord::Base
                                    
has_one :invoice
end

 

10.

You want to edit the script that was generated. From your terminal window, enter the following command:

                                 
gedit app/models/invoice.rb
                              

 

11.

Replace the contents of the file with the following and then save and close the file.

                                 
                                   
class Invoice < ActiveRecord::Base
                                    
belongs_to :order
end

 

12.

You can generate the scaffold for the order model using the following command:

                                 
ruby script/generate scaffold order
                              

 

13.

You want to edit the html that was generated. From your terminal window, enter the following command:

                                 
gedit  
                                  
app/views/orders/list.rhtml
                                
                              

 

14.

Replace Order.content_columns with Order.columns in this file. Then save and close the file.

 

15.

You can generate the scaffold for the invoice model using the following command:

                                 
ruby script/generate scaffold invoice
                              

 

16 .

You want to edit the html that was generated. From your terminal window, enter the following command:

                                 
gedit  
                                  
app/views/invoices/list.rhtml
                                
                              

 

17.

Replace Invoice.content_columns with Invoice.columns in this file. Then save and close the file.

 

18.

You can view the application. Open a browser window and enter the following URL:

                                 
http://localhost:3000/orders
                              

Create a new order.

 

19.

Controller files are generated by Rails by default when a Scaffold is created. These controller files have some default actions, which need to be modified if you want the applications to behave in manners other then the default generated by Rails. From your terminal window, enter the following command:

                                 
gedit app/controllers/invoices_controller.rb
                                  

 

20.

Replace the create section of the file with the following and then save and close the file.

                                 
def create 
   @order = Order.find(:first, :order => "id DESC")
                                  
@invoice = Invoice.new(params[:invoice])
if @invoice.save
if !@order.nil?
@order.invoice = @invoice
end
flash[:notice] = 'Invoice was successfully created.'
redirect_to :action => 'list'
else
render :action => 'new' end
end

 

21.

You can view the application. Open a browser window and enter the following URL:

                                 
http://localhost:3000/invoices
                              

Create a new invoice. After creating the invoice, you find it is associated with the last order you created.

 

Back to Topic List

12. RoR: One-To-Many Relationship between tables

One-To-Many relationship represents one row in table A is associated with an arbitrary number (may be zero, one, more than one) of rows in table B. To create a Rails application with One-To-Many Relationship between tables, perform the following steps.

1.

Generate the models for order and invoice. From your terminal window, execute the following command:

                                 
ruby script/generate model line_item
                              

 

2.

You want to edit the script that was generated. From your terminal window, enter the following command:

                                 
gedit  
                                  
db/migrate/004_create_line_items.rb
                                  

 

3.

Replace the self.up section with the following content and then save and close the file.

                                 
def self.up
                                  
create_table :line_items do |t|
t.column :order_id, :integer
t.column :subject, :string
t.column :description, :string
end
end

 

4.

You can now rake the database migration to generate target tables. From your terminal window, enter the following command:

                                 
rake db:migrate
                              

 

5.

You want to edit the script that was generated. From your terminal window, enter the following command:

                                 
gedit app/models/order.rb
                                  

 

6.

Add the has_many :line_items entry in the file as follows. Then save and close the file.

                                 
class Order < ActiveRecord::Base
                                  
has_one :invoice

has_many :line_items
end

 

7.

You want to edit the script that was generated. From your terminal window, enter the following command:

                                 
gedit app/models/line_item.rb
                                  

 

8.

Replace the contents of the file with the following and then save and close the file.

                                 
                                   
class LineItem< ActiveRecord::Base
                                    
belongs_to :order
end

 

9.

You can generate the scaffold for the line_item model using the following command:

                                 
ruby script/generate scaffold line_item
                              

 

10.

You want to edit the html that was generated. From your terminal window, enter the following command:

                                 
gedit  
                                  
app/views/line_items/list.rhtml
                                
                              

 

11.

Replace LineItem.content_columns with LineItem.columns in this file. Then save and close the file.

 

12.

You can view the application. Open a browser window and enter the following URL:

                                 
http://localhost:3000/line_items
                              

Create a new order.

 

13.

You want to modify the controller file. From your terminal window, enter the following command:

                                 
gedit app/controllers/line_items_controller.rb
                                  

 

14.

Replace the contents of the file with the following and then save and close the file.

                                 
def create
                                  
@order = Order.find(:first, :order => "id DESC")
@line_item = LineItem.new(params[:line_item])
if @line_item.save
if !@order.nil?
@order.line_items << @line_item
end
flash[:notice] = 'LineItem was successfully created.'
redirect_to :action => 'list'
else
render :action => 'new'
end
end

 

15.

You can view the application. Open a browser window and enter the following URL:

                                 
http://localhost:3000/line_items
                              

Create 2 line items. You will find they are  associated with the last order you created.

 

Back to Topic List

13. RoR: Many-To-Many Relationship between tables

Many-To-Many relationship represents an arbitrary number of rows in table A are associated with an arbitrary number of rows in table B. To create a Rails application with Many-To-Many Relationship between tables, perform the following steps.

1.

Generate the models for article, author and articles_author. From your terminal window, execute the following command:

                                 
ruby script/generate model article
ruby script/generate model author
                                 
ruby script/generate model articles_author
                              

 

2.

You want to edit the script that was generated. From your terminal window, enter the following command:

                                 
gedit  
                                  
db/migrate/005_create_articles.rb
                                  

 

3.

Replace the self.up section with the following content and then save and close the file.

                                 
def self.up
                                  
create_table :articles do |t|
t.column :title, :string
t.column :abstract, :string
end
end

 

4.

You want to edit the script that was generated. From your terminal window, enter the following command:

                                 
gedit  
                                  
db/migrate/006_create_authors.rb
                                  

 

5.

Replace the self.up section with the following content and then save and close the file.

                                 
def self.up
                                  
create_table :authors do |t|
t.column :name, :string
t.column :vocation, :string
end
end

 

6.

You want to edit the script that was generated. From your terminal window, enter the following command:

                                 
gedit  
                                  
db/migrate/007_create_articles_authors.rb
                                  

 

7.

Replace the self.up section with the following content and then save and close the file.

                                 
def self.up
                                  
create_table :articles_authors do |t|
t.column :article_id, :integer
t.column :author_id, :integer
end
end

 

8.

You can now rake the database migration to generate target tables. From your terminal window, enter the following command:

                                 
rake db:migrate
                              

 

9.

You want to edit the script that was generated. From your terminal window, enter the following command:

                                 
gedit app/models/article.rb
                                  

 

10.

Replace the contents of the file as follows. Then save and close the file.

                                 
                                   
class Article < ActiveRecord::Base
                                    
has_and_belongs_to_many :authors set_sequence_name "ARTICLES_AUTHORS_SEQ"
end

 

11.

You want to edit the script that was generated. From your terminal window, enter the following command:

                                 
gedit app/models/author.rb
                                  

 

12.

Replace the contents of the file as follows. Then save and close the file.

                                 
                                   
class Author < ActiveRecord::Base
                                    
has_and_belongs_to_many :articles set_sequence_name "ARTICLES_AUTHORS_SEQ"
end

 

13.

You can generate the scaffold for the article model using the following command:

                                 
ruby script/generate scaffold article
                              

 

14.

You want to edit the html that was generated. From your terminal window, enter the following command:

                                 
gedit  
                                  
app/views/articles/list.rhtml
                                
                              

 

15.

Replace Article.content_columns with Article.columns in this file. Then save and close the file.

 

16.

You can generate the scaffold for the author model using the following command:

                                 
ruby script/generate scaffold author
                              

 

17.

You want to edit the html that was generated. From your terminal window, enter the following command:

                                 
gedit  
                                  
app/views/authors/list.rhtml
                                
                              

 

18.

Replace Author.content_columns with Author.columns in this file. Then save and close the file.

 

19.

You can generate the scaffold for the articles_author model using the following command:

                                 
ruby script/generate scaffold articles_author
                              

 

20.

You want to edit the html that was generated. From your terminal window, enter the following command:

                                 
gedit  
                                  
app/views/articles_authors/list.rhtml
                                
                              

 

21.

Replace ArticlesAuthor.content_columns with ArticleAuthor.columns in this file. Then save and close the file.

 

22.

You want to modify the controller file. From your terminal window, enter the following command:

                                 
gedit app/controllers/articles_controller.rb
                                  

 

23.

Replace the contents of the file with the following and then save and close the file.

                                 
def create
                                  
@author = Author.find(:first, :order => "id DESC")
@article = Article.new(params[:article])
if @article.save
if !@author.nil?
@author.articles << @article
end
flash[:notice] = 'Article was successfully created.'
redirect_to :action => 'list'
else
render :action => 'new'
end
end

 

24.

???. From your terminal window, enter the following command:

                                 
gedit app/controllers/authors_controller.rb
                                  

 

25.

Replace the contents of the file with the following and then save and close the file.

                                 
def create
                                  
@article = Article.find(:first, :order => "id DESC")
@author = Author.new(params[:author])
if @author.save
if !@article.nil?
@article.authors << @author
end
flash[:notice] = 'Author was successfully created.'
redirect_to :action => 'list'
else
render :action => 'new'
end
end

 

26.

You can view the application. From your browser window, enter the following URL:

                                 
http://localhost:3000/articles
                              

Create an article.

 

27.

Then from your browser window, enter the following URL:

                                 
http://localhost:3000/authors
                              

Create two authors.

 

28.

Now you can see the association between authors and articles by entering the following URL:

                                 
http://localhost:3000/articles_authors
                              

 

29.

Go back to the following URL and create 3 more articles

                                 
http://localhost:3000/articles
                              

 

30.

Then enter the following URL to see that the articles you just created are associated with the last author you created.

                                 
http://localhost:3000/articles_authors
                              

 

Back to Topic List

Summary

In this tutorial, you have learned how to:

 Installing Ruby on Rails with Oracle

Use Ruby to create a connection to Oracle Database

 Query Data
 Bind Variables
 Define Datatypes
 Create and manage transactions
 Use PL/SQL
 Use LOB to store and retrieve Images

Use XML

Use ActiveRecord

Create applications using Rails

Handle various relationship between tables

Back to Topic List

Related Information

 http://www.rubyonrails.com/
 http://www.ruby-lang.org/
 Oracle Database Express Edition on OTN
 Ruby on Rails with Oracle FAQ
 Ruby/Ruby On Rails Forum on OTN

Back to Topic List

Appendix: Ruby Primer

This part of the tutorial gives you an overview of the Ruby language. The objects you will encounter are listed below. If you are familiar with Ruby, skip this section and move onto the next.


Variable

$var # global variable
@var  # instance variable of self
VAR  # constant
SomeClass::VAR # constant within a class
var or _var  # local variable


Pseudo Variables


self, nil, true, false

FILE # current source file
LINE # current line

Array


[1,2,3]

[“dog”, “cat”, “pig”], equivalent to %w(dog cat pig)

[ 1, 'cat', 3.14 ]  

Hash


{expr1 => exprA, expr2 => exprB }

hashvar = { 'dog' => 'Frank', 'cat' => 'Sissi', 'donkey' => 'Tim' }
hashvar.length # 3
hashvar['dog']   # "Frank"
hashvar['cow'] = 'Ethan'

Range


expr1 .. expr2 # inclusive
expr1 ... expr2 # excludes the last element

String literals


# string enquoted with double quotes is subjected to expression substitution
"remember to escape \" and \\ #{expression_substituted}"
# string enquoted with single quote is not evaluated
'remember to escape \' and \\ #{expression_not_substituted}'


Iterators

 

[ 1, 1, 2, 3, 5 ]. each {|val| print val, " " } # 1 1 2 3 5

  3.times do print "Ho! " end # Ho! Ho! Ho!

Method invocation

method(args1, arg2)

method(*array), equivalent to method(array_member1, array_member2, …)

Operators

+, -, *, /, %, **, &, |, ^, <<, >>, &&, ||
foo += 5
foo, bar, baz = 1, 2, 3
foo, bar = 1          # foo = 1; bar = nil
foo,*bar = 1, 2, 3          # equivalent to foo = 1; bar = [2, 3] ( the * multiple assignment is used to assign to an array)


begin block

# begin is different from the uppercase BEGIN, which has a totally different meaning
# If exception occurs in expr1, rescue will execute expr2. The matching of error_type is
# done by kind_of?. else clause has to follow after rescue and is executed if no exception
# occurs in expr1. The ensure clause is always executed as the block is exited even if an
# uncaught exception is in the process of being propagated.

begin
  expr1..
[ rescue [error_type,..]
  expr2..]..
[ else
  expr3..]
[ ensure
  expr4..]
end


Blocks

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


Control Structure

false and nil are false, everything else are true.

if expr [ then]
  expr...
[ elsif expr [ then]
  expr...]...
[ else
  expr...]
end

unless expr [ then]
  expr...
[ else
  expr...]
end

expr1 if expr2          # if expr2 is true, execute expr1
expr1 unless expr2   # if expr2 is false, execute expr1

# case comparison is via the === operator
case expr
[ when expr [, expr]...[ then]
  expr..]..
[ else
  expr..]
end

while expr [ do]
  #code goes here
end

until expr [ do]
  #code goes here
end

expr1 while expr2              # keep evaluating expr1 while expr2 is true.
expr1 untill expr2              # keep evaluating expr1 until expr2 is true
begin expr1 until expr2     # evaluating expr1 at least 1 time until expr2 is true

for lhs... in expr [ do]
  expr..
end

# There are 2 special keywords that can be used in the loop body:
next      #jump to next iteration of the inner-most loop

redo    #restart the current iteration of the most inner-most loop without checking
           #loop condition

Back to Topic List

Appendix: How to Modify Database Tables by Rails Migration

In Rails, if you want to add the column "t.column :price, :float" in the table "comics", perform the following steps:

1.

You can now generate the comic model. From your terminal window, execute the following command:

                                 
ruby script/generate migration add_columns
                              

 

2.

You want to edit the script that was generated. From your terminal window, enter the following command:

                                 
gedit db/migrate/008_add_columns.rb
                                  

 

3.

Replace the self.up section with the following content and then save and close the file.

                                 
 def self.up
     add_column :comics, :author, :string
  end
                              

 

4.

You can now rake the database migration to generate target tables. From your terminal window, enter the following command:

                                 
rake db:migrate
                              

Note: To remove a column we can add a line like "remove_column :comics, :price" in the self.up method; To rename a column we can add a line like "rename_column :comics, :price, :new_price" in the self.up method; To change a column we can add a line like "change_column :comics, :price, :integer" in the self.up method.
Moreover we can rollback the Migration operation by issuing the command "rake db:migrate VERSION=xx", where the xx is the version you expect to rollback to.

 

Back to Topic List

Appendix: Installing Ruby on Rails with Oracle

This part of the tutorial shows you how to install Oracle Instant Client, Ruby , Ruby/OCI8, RubyGems and Rails, which you need to run Ruby on Rails applications with Oracle Database.

1.

Download the Oracle Instant Client from OTN. Open a terminal window and execute the following commands:

                                 
su
<password to root is oracle>
                              

 

2.

Oracle Instant Client is a software that lets you run your applications without installing the standard Oracle client or having an ORACLE_HOME. To install Oracle Instant Client, run the following commands.

                                 
rpm -ivh oracle-instantclient-basic-10.2.0.3-1.i386.rpm
rpm -ivh oracle-instantclient-devel-10.2.0.3-1.i386.rpm
                              

 

3.

You need to add the directory where libclntsh.so.10.1 exists to the library search path indicated by the environment variable LD_LIBRARY_PATH. Enter the following command to update your bash profile.

                                 
gedit /etc/bashrc
                              

 

4.

Add the following lines to the end of the /etc/bashrc file, save the file and close the editor.

                                 
                                   
                                     
source /usr/lib/oracle/xe/app/oracle/product/10.2.0/server/bin/oracle_env.sh
export LD_LIBRARY_PATH=/usr/lib/oracle/10.2.0.3/client/lib:$LD_LIBRARY_PATH
                                  
                                
                              

 

5.

Execute the oracle_env.sh script by executing the following command:

                                 
                                   
                                     
source /etc/bashrc
                                  
                                
                              

 

6.

To install Ruby, perform the following steps:

                                 
tar -xzvf ruby-1.8.6.tar.gz
cd ruby-1.8.6
./configure
make
make install 
                              

 

7.

RubyGems is the Ruby standard for publishing and managing third party libraries. To install RubyGems, perform the following steps:

                                 
                                   
cd ..
tar -xzvf rubygems-0.9.4.tar.gz
cd rubygems-0.9.4
ruby setup.rb
                                
                              

 

8.

Ruby/OCI8 is a ruby interface for Oracle using OCI8 API. To install Ruby/OCI8, run the following commands:

                                 
                                   
                                     
cd ..
tar -xzvf ruby-oci8-0.1.16.tar.gz
cd ruby-oci8-0.1.16
ruby setup.rb config --with-instant-client
ruby setup.rp setup
ruby setup.rb install
                                  
                                
                              

 

9.

The Ruby DBI module provides a database-independent interface for Ruby scripts similar to that of the Perl DBI module. To install Ruby/DBI, run the following commands:

                                 
                                   
                                     
                                       
cd ..
tar -xzvf dbi-0.1.1.tar.gz
                                    
cd ruby-dbi
ruby setup.rb config --with=dbi
ruby setup.rp setup
ruby setup.rb install
                                  
                                
                              

 

10.

To install Rails and its dependencies locally, run the following commands:

                                 
                                   
                                     
                                       
cd ..
gem install activesupport-1.4.2.gem
gem install actionpack-1.13.3.gem
gem install active record-1.15.3.gem
gem install actionwebservice-1.2.3.gem
gem install rake-0.7.3.gem
gem install actionmailer-1.3.3.gem
gem install rails-1.2.3.gem
                                    
                                  
                                
                              

If you can access the remote gems from http://gems.robyforge.org, you can install rails and its dependencies remotely by running the following command. This is much more convenient because you don't need to download gem files manually.

gem install rails --include-dependencies

 

Back to Topic List

 Place the cursor over this icon to hide all screenshots.

 

Left Curve
Popular Downloads
Right Curve
Untitled Document