Contributed by
July 2008 [Revision number: V6.1-1]
This tutorial gives you a quick 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
application development tasks.
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 Projects 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
Follow these steps to create a Ruby
project.
If you have not 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 a blank spot in the Projects window and choose
New Project from the pop-up menu, as shown in the following
figure.
In the New Project wizard, select Ruby in the Categories pane,
select Ruby Application
in the Projects pane, as shown in the following figure,
and click Next.
Type a project name, for example
simple_ruby_application,
as shown in the next figure.
(Optional) Select a Ruby Platform.
To
add other Ruby platforms to the list, click Manage to
open the Platform manager. Click the manager's help
button to learn how to register your installed Ruby platforms.
Click Finish.
The IDE displays the main.rb file in the editor,
as shown in the following figure.
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 (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 product item class.
Next you create 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 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,
as shown in the following figure.
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 code.
# Class to represent an item sold in the store.
class Item
def initialize(id, type, price)
@id, @type, @price = id, type, price
end
def to_s
"Item #{@id} is a #{@type}: Price $#{@price}"
end
# Returns an array of all the items sold in the store.
def self.load_item_data
items = []
File.open("data.txt") do |data_file|
data_file.readlines.each do |line|
items << Item.new(*line.split("\s"))
end
end
items
end
end
Right-click the source text and choose Format
from the pop-up menu to reformat the code.
Place the cursor on the class Item
line and press Shift-Enter to open a line at the top of the class block.
This step, combined with the next three steps, shows how to use
code completion. Place the cursor in the blank 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.
This attr_accessor method call
creates the id, type,
and price getter methods.
These getter methods enable
users of the Item class
to access the values of the id, type,
and price instance variables.
Next, you change the argument for the open
method to a constant. Select the "data.text" string,
including the quote marks.
You can use the Alt-Shift-Period (.) key combination
(Ctrl-Shift-Period on the Mac),
which selects the enclosing block,
to select the string.
Notice the lightbulb icon that appears in the left margin.
This icon indicates that the IDE offers hints about the
selection.
Place the cursor over the lightbulb, as shown in the following
figure, to view the hints.
Press Alt-Enter (Ctrl-Shift-Enter on the Mac) to display the
quick fix options.
The IDE displays the available quick fixes for the selected
string, as shown in the next figure.
Select Introduce Constant and press Enter.
The Introduce Constant dialog box appears.
Type data_file in the Name text box, and click OK.
The IDE adds a declaration for the constant and changes the
argument to use the constant instead of the string.
Notice how the IDE changed the constant name to all uppercase
letters. By convention, constant variables are
spelled by using uppercase letters and inserting underscores
as word separators.
The completed script should look like the following
code sample.
# Class to represent an item sold in the store.
classItem# TODO Comment
DATA_FILE = "data.txt"
attr_accessor :id, :type, :pricedef initialize(id, type, price)
@id, @type, @price = id, type, price
enddef to_s
"Item #{@id} is a #{@type}: Price $#{@price}"end# Returns an array of all the items sold in the store.
defself.load_item_data
items = []
File.open(DATA_FILE) do |data_file|
data_file.readlines.each do |line|
items << Item.new(*line.split("\s"))
endend
items
endend
Create the Data File
In the Projects window, right-click 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 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:
Item.load_item_data.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 next, 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.
Press Ctrl and drag the cursor over one of the
calls to the gsub method.
The IDE displays the RDoc documentation for the gsub
method, as shown in the next figure.
If the Rdoc documentation is wider or longer
than the display box, you can click the method or class
and press Ctrl-Shift-Space (Cmd-Shift-Space on the Mac) to
view the Rdoc in a display box with scroll bars.
Open a line at the top of the file 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 the characters
it and press Ctrl-Space.
Only one available import starts
with "it", which is item, as shown in the next figure.
Press
Tab to accept the choice, and press Enter.
Click one of the usages of the line_item variable
and press Ctrl-R.
The IDE highlights the variable in blue to indicate that
Instant Rename mode is active, as shown in the following
figure.
Type print_line and press Enter.
The IDE changes all occurrences of line_item to
the new name.
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.
For More Information
To learn more about using hints and quick fixes,
see, Ruby
Hints.
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.
You create a Rails project by right-clicking a blank
spot 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 a project node in the Projects 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.
Just as with Ruby projects, you can select the Ruby Platform
from the drop-down list. If you have installed a platform that
does not appear on the drop-down list, click Manage to add
that platform.
By default, the IDE sets up the project to use three MySQL databases,
which are given the names project_development,
project_test, and
project_production, where project is
the name of your Rails project. To change the default configurations,
you can edit the database.yml file, which opens in
the editor after you create the project. Alternatively, you can
click Next in the Project wizard to display the Database Configuration
page, which is shown in the following figure.
You can change a project's settings by right-clicking
the project node and choosing Properties from the pop-up menu.
The Project Properties dialog box,
which is shown in the following figure,
enables you to configure the project's platform, server, mode,
encoding, and rake arguments. You can also create different
configurations
for a project, and use this dialog box to switch
configurations.
Try It
Follow these steps to create a Ruby on Rails
project.
Right-click 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.
Name the project, for example,
simple_rails_application.
Click Finish.
This tutorial does not use a database, so you
do not need to perform any database configurations.
Examine the logical view of the file structure in the Projects
window.
Right-click 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 Projects window.
The following figure shows the windows side by side,
to make it easy to compare the two views.
To have the Projects window display
the physical layout instead of the logical layout,
choose Tools > Options
from the main menu, and click Ruby.
Click the Miscellaneous tab, clear the Show Logical Project
View checkbox, and restart the IDE.
Right-click on the project's node in the Files window.
Notice the different
menu options, compared to the pop-up menu
in the Projects window.
For example, the pop-up menu for the 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.
For More Information
For more information about database configuration from
the Project Wizard, see
Using Database Servers With JRuby
, and the New Ruby on Rails Application Wizard: Database
Configuration
help topic.
Working With Ruby on Rails Files
Note: This section is written for
Rails 2.
Just as with Ruby projects, you can open a file
in the editor by
double-clicking the file's node in either the Projects
window or the Files window.
Alternatively, you can press
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 the
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, and
you obtain the data from a
YAML file.
Note: Typically, with a Rails project, you
base your model classes on database tables. However, to
make this example quick and simple, the application obtains
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, expand Configuration, and double-click
environment.rb to open the file in the editor.
Scroll down to the following comments (around line 20).
# Skip frameworks you're not going to use (only works if using vendor/rails).
# To use Rails without a database, you must remove the Active Record framework
# config.frameworks -= [ :active_record, :active_resource, :action_mailer
Uncomment the third line, as shown in the following
code.
# Skip frameworks you're not going to use (only works if using vendor/rails).
# To use Rails without a database, you must remove the Active Record framework
config.frameworks -= [ :active_record, :active_resource, :action_mailer ]
You can click the Uncomment button (
)
to uncomment selected lines.
Following the Rails principle of
convention over configuration,
a Rails 2 application tries to access the database that
is specified in the database.yml file. Because
this application is not using a database, you must remove the
Active Record framework from the environment configuration
so that the application does not try to access a database.
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 in the following figure.
Type Item in the Arguments text box, and
click OK.
The generator 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. By default,
the generator 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
classItemDATA_FILE="data.yml"
attr_accessor :id, :type, :pricedef initialize(attributes)
@id = attributes['id']
@type = attributes['type']
@price = attributes['price']
enddef to_s
"Item #{@id} is a #{@type}: Price $#{@price}"end# Returns an array of all the items sold in the store.defself.load_item_data
YAML.load_file(DATA_FILE).collect do |item_hash|
Item.new(item_hash)
endendend
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. The file's node
might not immediately appear in the Projects 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 in the following figure.
Type Item in the Name text box, type
index in the Views text box, and click OK.
The generator creates both the ItemController class
and the index.html.erb view, which is under the
Views > item node. In addition, the generator 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.
classItemController < ApplicationControllerdef index
@items = Item.load_item_data
endend
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.html.erb file, right-click
a line 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.html.erb 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 align="right"><%= number_to_currency(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 indicate modified files,
are no longer displayed.
Right-click the source text and choose Run from the pop-up menu.
The IDE sends the URL for the item controller and the index
action to the server, which in turn 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
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.root :controller => "welcome"
Replace the comment with the following code.
map.root :controller => "item"
To ensure that the server implements the routing changes,
click the server stop button that appears in the
lower right corner of the IDE, as shown in the
following figure.
Click Run Main Project to start the application in the browser.
To practice what you have learned, create another Rails project.
Have the project read and display the entries in a task list.
For More Information
The NetBeans
Ruby and Rails Learning Trail
provides many other screencasts and tutorials
about Ruby and Rails support in the IDE.
The
Ruby on Rails web site
contains screencasts, presentations, tutorials, and samples.
The IDE provides a sample Rails application.
To access the sample application, select File >
New Project from the main 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.
To obtain support and stay informed of the latest
changes to the NetBeans Ruby development features,
join the and
mailing lists.