Contributed by
December 2007 [Revision number: V6.0-3]
This tutorial gives you a whirlwind tour of Ruby and Ruby on Rails
application development in the NetBeans IDE. The tutorial shows you how to
use the IDE's Ruby support to perform some of the typical phases
of application development.
The tutorial is designed so that you do not need to
go through it in any particular order. You might want
to skim over it quickly and then return to each section
as time allows. If you prefer a step-by-step tutorial,
you might want to first
try
Creating a Ruby Weblog in 10 Minutes.
A project is the equivalent of your working environment for
an application. When you create a new Ruby project, you have
the choice of creating a project from existing files, or creating
a new set of folders with templates for your Ruby project.
Note: When you open an existing Ruby or JRuby project
that you built outside of the IDE, the only NetBeans software-related
modification that the IDE makes to the project is to
create an nbproject folder, which contains
NetBeans metadata.
You can have several projects open in the IDE at the same time. When
you have more than one project open, you must specify which
project is the main project. The main project is the project that
the IDE runs when you click the Run Main Project button. To switch
the main project, right-click on a project in the Project's window
and choose Set as Main Project.
When you create a new Ruby project, the IDE creates a
file named main.rb by default, and sets this file as
the main script. When you click the Run Main Project
button (
),
the IDE saves all file changes and runs the main script. To switch to
a different start script, right-click the Project node
in the Projects window and choose Properties from
the pop-up menu. Select the Run category and, in the
Main Script text field, type the file name.
Note: The main.rb file is created
for Ruby projects. When you create a Ruby on Rails
project, as shown in the
Creating a Ruby on Rails Project section, the IDE
does not create
a main.rb file.
Try It
Below are the steps to create a Ruby
project.
If you haven't done so already,
start the IDE by using the appropriate step
from the following list:
Windows, Solaris and Linux.
Double-click the NetBeans desktop icon.
Mac. Double-click the NetBeans
icon in the installation folder.
Right-click on a blank spot in the Projects window and choose
New Project from the pop-up menu.
In the New Project wizard, select Ruby in the Categories pane,
select Ruby Application
in the Projects pane, and click Next. If this project is the
first Ruby project that you have opened or created, a dialog
might appear asking you to choose a Ruby interpreter. Select
one of the interpreter choices and click OK.
Name the project, for example simple_ruby_application,
and click Finish.
The IDE displays the main.rb file in the editor.
Notice how the code calls puts to display
the string "Hello World".
The Project window shows a logical view of the project
files. Click the Files tab to view the physical
layout, then switch back to the Projects window. With Ruby
projects, the views are very similar.
Click the Run Main Project button
()
to run the application.
The IDE displays the output in a window at the bottom of
the IDE, as shown below.
Working With Ruby Files
You work with your Ruby project files similar to how you
would work with them from a text editor. You open a file by
double-clicking on the file's node in either the Projects
window or the Files window. You can also press
Alt-Shift-O (use Ctrl-Shift-O on the Mac)
to access files by name.
The IDE's editor offers many features to facilitate your programming
tasks. You
will learn about some of the basic editing
features in this section. A comprehensive list of
the editing features can be found on the NetBeans
Ruby
Editing wiki page.
Try It.
Follow these steps to create a simple Ruby project that displays
a product list. First, you create a class for an individual product
item. Next you create a class for the item list and a data file
to supply the product data. Last,
you edit the main.rb file to display the list. As you develop
the code, the steps will also introduce editing features.
Create the Item Class
Create a Ruby project, or use the one that you
created in the previous section.
In the Projects window, create a class file by
right-clicking the Source Files node and
choosing New > Ruby Class from the pop-up menu. Type
Item in the Class text box
and click Finish.
The IDE creates a file named item.rb and opens the file
in the editor.
Replace the contents of the item.rb file with the
following incorrect code. You will fix the code in the
remaining steps.
class Item
def initialize(id, type, price)
end
def simple_method(id, type, price)
@id = id
@type = type
@price = price.to_f
end
def to_s
"Item #{@id} is a #{@type}: Price $#{@price}"
end
end
Right-click in the source and choose Format
from the pop-up menu to reformat the code.
Notice the gray squiggly lines under the arguments
for the initialize method, as shown in the following
figure. These lines identify
unused variables. You will fix this error in the next
two steps.
Place the cursor on @type in the simple_method
and press
Alt-Shift-Period (use Ctrl-Shift-Period on the Mac)
to select the line. Press the key combination
one more time to select the block, as shown
in the following figure.
Right-click
in the source and choose Cut from the pop-up menu.
Place the cursor on the beginning of the constructor
(initialize
method) and press Shift-Enter to add a new line under the
current line. Right-click
in the new line and choose Paste from the pop-up menu.
The purpose of the simple_method was
to hold the code required for the previous steps. You
can now delete this method. First, place the cursor on
the end
statement for the
simple_method.
Notice that the IDE highlights the corresponding
def.
Press Alt-Shift-Period
(use Ctrl-Shift-Period on the Mac)
to select the method, then press Backspace to
delete it.
Place
the cursor on the blank line and press Ctrl-E
(Use Cmd-E on the Mac) to
remove it.
This step along with the next two steps shows how to use
code completion. Open up a line at the top of the class block,
then place the cursor in the line, type attr_a,
and press Ctrl-Space (if Ctrl-Space does not work on your
system, use Ctrl-\).
The IDE displays a list of possible code completions, as
shown in the following figure.
Select attr_accessor :attr_names rw, and
press Enter.
The IDE completes the code and selects attr_names
for editing, as shown in the next figure.
Type id, :type, :price to
complete the statement and press Enter.
The statement should look like the
following code.
attr_accessor :id, :type, :price
Select each of the arguments to the
attr_accessor method and notice how the
IDE highlights each attribute's use.
The completed script should look like the following
code sample.
class Item
attr_accessor :id, :type, :price
def initialize(id, type, price)
@id = id
@type = type
@price = price.to_f
end
def to_s
"Item #{@id} is a #{@type}: Price $#{@price}"
end
end
Create the ItemsList Class
In the Projects window, create another class file by right-clicking
the Source Files node and choosing New > Ruby Class from the pop-up
menu. Type ItemsList in the Class text box and click Finish.
Note that the IDE names the file items_list.rb.
Replace the contents of the items_list.rb file
with the following statements.
class ItemsList
DATA_FILE="data.txt"
attr_accessor :items
def initialize
@items = ItemsList.load_item_data
end
private
def self.load_item_data
items = []
File.open(DATA_FILE) do |data_file|
data_file.readlines.each do |line|
items << Item.new(*line.split("\s"))
end
end
items
end
end
Open up a line above the Class definition and type
require ' (single quote).
Notice how the IDE provides
the ending single quote and places the cursor
between the quotes, as shown in the following
figure. The IDE automatically inserts and removes
matching delimiters, such as
quotes, braces,
and brackets, as well as end statements
for code blocks.
With the cursor inside the single quotes, type it and press Ctrl-Space.
There is only one available import that starts
with "it", item, as shown in the next figure. Press
Tab to accept that choice.
Create the Data File
In the Projects window, right-click on the Source Files node
and choose New > Other from the pop-up menu.
Select Other in the Categories pane and select Empty File in
the File Types pane,
then click Next.
Type data.txt in the
File Name text box.
Ensure that the Folder is set to
lib,
and click Finish.
Note: You are placing the text file
in the lib folder because, by default,
when you run the project from the IDE,
the default working directory is the lib
folder.
Paste the following text into the data.txt
file.
BF15678 book 25.32
C29589 cd 18.95
F89028 beverage 2.00
BN98232 book 45.33
BF15890 book 15.98
Create the Main Script and Run the Application
In the Projects window, double-click main.rb
to display the file in the editor window. Replace
the contents with the following statements, which
display the list of items:
require 'items_list'
items_list = ItemsList.new
items_list.items.each do |item|
line_item = item.to_s
line_item.gsub!(/book/, 'fiction \0') if item.id =~ /\AB[FN]/
line_item.gsub!(/fiction/, 'non-\0') if item.id =~ /\ABN/
puts line_item
end
puts "\n"
The code that you just copied contains two Regexp objects;
/\AB[FN]/ and /\ABN/.
Place the cursor inside one of the
Regexp objects, as shown below, and press
Ctrl-Space. The IDE displays a list of
regular expression characters
and character combinations. Look at
the data that you inserted into data.txt and guess
which items match each of
the two regular
expressions.
To run the project, click the Run Main Project
button in the main toolbar.
The IDE saves all your changes and runs the main.rb
script. The application output appears in the Output
window, as shown in the following figure.
To practice what you have learned, create another
Ruby project. Have the project read and display
the entries in a task list.
Note: This section is written for Rails 1.2.5 and Rails 1.2.6.
Creating a Ruby on Rails project in the IDE is very
similar to using the rails command in a terminal
window. In fact, when you create a project, the IDE creates
the same folders and files that a rails command
would create.
You create a project by right-clicking in the Projects
window and choosing New Project from the pop-up menu. You select
Ruby from the Categories pane, and you
select either Ruby on Rails Application or Ruby on Rails Application
With Existing Sources from the
Projects pane.
You can have several projects
open in the IDE at the same time. The node for the
main project, which
is the project the NetBeans actions act on, is shown
in bold. To switch the main project,
right-click on a project in the Project's window and choose
Set as Main Project.
As shown in the following figure, the second page of the New Project wizard
enables you to name the project and specify its location.
A drop-down list provides the names of several supported
database servers. The IDE uses the selected database
server as well as the Access Database Using JDBC option
to determine how to write the contents for the database.yml file.
Try It
Follow these steps to create a Ruby on Rails
project.
Right-click on a blank spot in the Projects window and choose
New Project from the pop-up menu.
In the New Project wizard, select Ruby in the Categories pane,
select Ruby on Rails Application
in the Projects pane, and click Next. If this project is the
first Ruby project that you have opened or created, a dialog
might appear asking you to choose a Ruby interpreter. Select
one of the interpreter choices and click OK.
Name the project, for example simple_rails_application.
Next, choose the database server that you will use
with the application. If you are using JRuby, you
must choose
MySQL, PostgresSQL, Oracle, HSQLDB, or Java DB (also known as Derby).
The IDE uses this information to seed the
database.yml file.
Note: If you plan to use this project solely for
this tutorial, you will not be accessing any databases,
so you can accept the default database settings.
If you are using JRuby and you are accessing
a database server other than
MySQL, you must select the Access Database Using JDBC checkbox.
If your database server is MySQL, the use of JDBC is optional.
When this checkbox is checked, the IDE adds statements
to the environment.rb file to use the ActiveRecord-JDBC
gem.
Note: To use a JDBC connection, you must obtain a
JDBC 3.0 client driver for your database server, and put a
copy of the JDBC driver in the JRuby/lib folder.
Click Finish.
Examine the logical view of the file structure in the Projects window.
Right-click on the project's node (the root node for the project)
and notice the menu options.
Click the Files tab and compare this physical file structure
with the logical view that is presented in the Project's window.
The following figure shows the windows side by side,
to make it easy to compare the two views.
Right-click on the project's node in the Files window
and notice the different
menu options, as compared to the pop-up menu in the Projects window.
For example, the pop-up menu for project's node in
the Projects window provides the Generate action,
Run Rake Task action, and the Rails Console action, in
addition to many other Rails specific actions.
Working With Ruby on Rails Files
Note: This section is written for Rails 1.2.5 and Rails 1.2.6.
In addition to Ruby projects,
NetBeans Ruby support enables you to work with Ruby on Rails
projects. Rails is a framework that enables you to quickly
create database-backed web applications that are based on the
model-view-controller (MVC) architecture.
Just as with Ruby projects, you can open a file
in the editor by
double-clicking on the file's node in either the Projects
window or the Files window, or by pressing
Alt-Shift-O (use Ctrl-Shift-O on the Mac)
to access a file by name.
The pop-up menus for the nodes in the Project window
provide easy access to Rails scripts and Rake tasks, such as
the generate script for generating code,
and the db:migrate task for migrating to
a specific version of the database tables.
The IDE understands the relationships between
the file types, and makes it easy to navigate
to associated files. For example, if you are
editing a view file, you can use the pop-up
menu to navigate to the associated action
file or test.
As with all NetBeans projects, you can run your
application by clicking the Run Main Project button. The
IDE saves all file changes, starts the web server, if necessary,
then displays the
welcome page in your browser. You can also use the
Run File menu action in the editor to open in
the browser the relevant URL to whatever
controller, action, view, or helper you are editing.
Try It
Complete the following steps to create a Rails version
of the sample project presented in the
Working With Ruby Files section. In this variation,
the constructor takes a hash instead
of positional arguments,
you get the data from a YAML file,
and the ItemsList functionality has been moved
to the Item class.
Note: Typically, with a Rails project, you
base your model classes on database tables. However, to
make this example quick and simple, the application gets
its data from a YAML file.
Create the Model Class
Create a Ruby on Rails project, or use the one that you
created in the previous section.
In the Projects window, right-click the Models
node and choose Generate from the pop-up menu.
The Rails Generator dialog box opens, with model
selected in the Generate drop-down list,
as shown below.
Type Item in the Arguments text box, and
click OK.
The IDE creates a file named item.rb and opens
the file in the editor. A node for the file appears under
the Models node in the Projects window. The IDE also creates a
test suite under
Unit Test, a test fixture under Test Fixtures, and a migration
under Database Migrations > migrate.
Replace the contents of the item.rb file with
the following code.
# Takes:
# :id => unique item id
# :type => type of item
# :price => price of the item
class Item
DATA_FILE="data.yml"
attr_accessor :id, :type, :price
def initialize(attributes)
@id = attributes['id']
@type = attributes['type']
@price = attributes['price'].to_f
end
def to_s
"Item #{@id} is a #{@type}: Price $#{@price}"
end
def self.load_item_data
YAML.load_file(DATA_FILE).collect do |item_hash|
Item.new(item_hash)
end
end
end
Create the Data File
The Item class requires the data.yml
file for its data. To create this file, right-click the project's
node in the Projects window, and choose New > Other from
the pop-up menu.
In the New File dialog box, select Ruby in the Categories pane,
select YAML file in the File Types pane, and click Next.
Type data in the File Name text box and click Finish.
The IDE creates a file named data.yml in the project's root
folder, and opens the file in the editor. Because the
file is in the root folder, you do not see it in the
logical view of the Project window. However, it does
appear in the Files window.
Replace the contents of the data.yml file with the
following text.
-
id: BF15678
type: book
price: 25.32
-
id: C29589
type: cd
price: 18.95
-
id: F89028
type: beverage
price: 2.00
-
id: BN98232
type: book
price: 45.33
-
id: BF15890
type: book
price: 15.98
Create the Controller and View
The model is ready. Now add the controller and the view.
In the Projects window, right-click the Controllers node and choose
Generate from the pop-up menu.
The Rails Generator dialog box opens with controller
selected in the Generate drop-down list,
as shown below.
Type Item in the Name text box, type
index in the Views text box, and click OK.
The IDE creates both the ItemController class
and the index.rhtml view, which is under the
Views > item node. In addition, the IDE creates
Functional Tests > item_controller_test.rb and
Helpers > item_helper.rb.
Replace the contents of the item_controller.rb file
with the following code.
class ItemController < ApplicationController
def index
@items = Item.load_item_data
end
end
The index action, which the controller
calls before calling the index view,
fills the @items global array
with the list of items.
To quickly access the index.rhtml file, right-click
in the index definition, and choose Navigate > Go to Rails
Action or View from the pop-up menu, as shown in the following figure.
Replace the contents of index.rhtml with
the following markup.
<h1>List of Items</h1>
<table border="1">
<tr><th>Id</th><th>Type</th><th>Price</th></tr>
<% for item in @items %>
<tr>
<td><%= item.id %>
</td>
<td><%= item.type %></td>
<td class="align-right"><%= '%.02f' % item.price %></td>
</tr>
<% end %>
</table>
The Ruby code that is embedded in the HTML iterates over the @items global array
that was defined by the index action in the controller.
Run the Application
Click the Save All button in the main toolbar to save all your
changes.
The asterisks (*) in the file tabs, which indicated modified files,
disappear.
Right-click in the editor and choose Run File.
The IDE sends the URL for the item controller and the index
action to the server, which, in turns sends the following
page to the browser.
Try clicking the Run Main Project to run the whole application.
Note that the standard Ruby on Rails welcome page appears. This is because
the router, by default, displays the Public > index.html file. You
will change the routing in the following steps.
In the Projects window, expand Public.
Right-click the index.html node and choose Delete from
the pop-up menu.
In the Projects window, expand the Configuration node and
double-click routes.rb to open it in the editor.
Look for the following comment.
# map.connect '', :controller => "welcome"
Replace the comment the following code shown in bold.
# You can have the root of your site routed by hooking up ''
# -- just remember to delete public/index.html.
map.connect '', :controller => "item"
To insure that the routing changes are picked up by the server,
click the server stop button that appears in the
lower right corner of the IDE, as shown below.
Click Run Main Project to start the application in the browser.
Practicing What You Have Learned
Now try building a project from scratch. Create a
Ruby on Rails project that displays the entries from a task list.
The
Ruby on Rails web site
contains screencasts, presentations, tutorials, and samples.
You can use the Plugins tool to download
and install the Ruby Depot sample application
(it might already be installed with
your version of the IDE). After installing the plugin,
right-click in the Projects window and choose New Project
from the pop-up menu. Expand Samples in the Categories
pane and select Ruby. Select Depot and click Next. Click
Finish and follow the instructions in the README that
appears in the browser.
Using the JRuby Interactive Ruby (IRB) Console
As you might guess, the JRuby Interactive Ruby (IRB) Console
is a module that lets you interactively enter Ruby statements, just
as you do with the Ruby IRB. In addition, the JRuby Interactive
Ruby (IRB) Console
provides interoperability with Java platform applications.
You open the console by choosing
Window > Other > Ruby Shell (IRB) from the main menu. The
console appears in the lower portion of the IDE, as shown in the
following figure.
The IRB Console is launched from the NetBeans installation
folder. To switch to another folder, type the following command,
replacing your-path with the path to the folder
that contains the Ruby files.
=> Dir.chdir("your-path")
Closing the console window does not stop the IRB
session. When you reopen the window, the command history
is still there. To stop a session, type quit
or exit in the console.
Try It
In the main menu, choose Window > Other > Ruby Shell (IRB)
to open the IRB console.
Type some Ruby constants to get familiar with the
environment, such as PLATFORM,
VERSION, ENV_JAVA, and ENV.
Type Object::constants to see all the top-level
constants.
Use the IRB to try out Ruby statements. For example,
type the following statements to see what Ruby
outputs:
Try to think of other Ruby statements you might want
to test, such as seeing what type of exception is thrown.
Try out the code completion pop-up feature. Type the
first few characters and press Tab to see a list of suggestions,
as shown in the following figure. You can continue typing
to narrow the list. Select your choice
and press Enter.
Press the Up-Arrow several times to scroll through the
command history and press the Down-Arrow to move down. Press Return
to re-execute a command.