FeaturesPluginsDocs & SupportCommunityPartners

Getting Started With Ruby and Rails

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.

Contents

Content on this page applies to NetBeans IDE 6.1

To complete this tutorial, you need the following software.

Software or Resource Version Required
NetBeans IDE with Ruby and Rails support Version 6.1
Rails Framework 2*

* The NetBeans IDE 6.1 with Ruby and Rails support includes the Rails 2.0.2 framework.

See Installing and Configuring Ruby Support for information about installing and configuring NetBeans Ruby support.

Creating a Ruby Project

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 ( 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.

  1. 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.
  2. Right-click a blank spot in the Projects window and choose New Project from the pop-up menu, as shown in the following figure.

    Selecting New Project in the pop-up menu
  3. 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.

    Selecting category and project type
  4. Type a project name, for example simple_ruby_application, as shown in the next figure.

    Typing the project name
  5. (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.

  6. 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 main.rb file in the editor
  7. 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.

  8. Click the Run Main Project button (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.

    Output Window

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

  1. Create a Ruby project, or use the one that you created in the previous section.
  2. 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.

    Choosing New Ruby Class in pop-up menu
  3. 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.
  4. 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
            
  5. Right-click the source text and choose Format from the pop-up menu to reformat the code.
  6. Place the cursor on the class Item line and press Shift-Enter to open a line at the top of the class block.

  7. 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.

    Code Completion List for attr_a
  8. 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.

    Completed Code
  9. Type id, :type, :price to complete the statement and press Enter.

    The statement should look like the following code.
      attr_accessor :id, :type, :price
            
  10. 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.

  11. 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.

  12. Place the cursor over the lightbulb, as shown in the following figure, to view the hints.

    Quick fix tooltip
  13. 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.

    Quick fix options
  14. Select Introduce Constant and press Enter.

    The Introduce Constant dialog box appears.

  15. 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.

  16. The completed script should look like the following code sample.

    # Class to represent an item sold in the store.
    class Item
      # TODO Comment
      DATA_FILE = "data.txt"
    
      attr_accessor :id, :type, :price
      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_FILE) do |data_file|
          data_file.readlines.each do |line|
            items << Item.new(*line.split("\s"))
          end
        end
        items
      end
    end
            

Create the Data File

  1. In the Projects window, right-click the Source Files node and choose New > Other from the pop-up menu.
  2. Select Other in the Categories pane and select Empty File in the File Types pane, then click Next.
  3. Type data.txt in the File Name text box.
  4. 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.

  5. 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

  1. 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"
            
  2. 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.

    Regular Expression Code Completion
  3. 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.

    RDoc for the gsub method

    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.

  4. 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.

    Delimiter Pair Matching
  5. 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.

    Code Completion for require statement
  6. Press Tab to accept the choice, and press Enter.
  7. 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.

    xxx
  8. Type print_line and press Enter.

    The IDE changes all occurrences of line_item to the new name.

  9. 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.

    simple_ruby_application Output
  10. 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

Creating a Ruby on Rails Project

Note: This section is specific to Rails 2.

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.

Page 2 of New Ruby on Rails Project Wizard

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.

Page 3 of New Ruby on Rails Project Wizard

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.

Project Properties dialog box

Try It

Follow these steps to create a Ruby on Rails project.

  1. Right-click a blank spot in the Projects window and choose New Project from the pop-up menu.
  2. In the New Project wizard, select Ruby in the Categories pane, select Ruby on Rails Application in the Projects pane, and click Next.
  3. Name the project, for example, simple_rails_application.
  4. Click Finish.

    This tutorial does not use a database, so you do not need to perform any database configurations.

  5. Examine the logical view of the file structure in the Projects window.
  6. Right-click the project's node (the root node for the project) and notice the menu options.
  7. 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.

    Comparison of Projects Window and Files Window

    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.

  8. 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

  1. Create a Ruby on Rails project, or use the one that you created in the previous section.
  2. In the Projects window, expand Configuration, and double-click environment.rb to open the file in the editor.

  3. 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
            
  4. 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 ( 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.

  5. 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.

    Rails Generator Invoked From the Model Node
  6. 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.

  7. 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']
      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
        YAML.load_file(DATA_FILE).collect do |item_hash|
          Item.new(item_hash)
        end
      end
    end
            

Create the Data File

  1. 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.
  2. In the New File dialog box, select Ruby in the Categories pane, select YAML File in the File Types pane, and click Next.
  3. 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.
  4. 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

  1. 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.

    Rails Generator Invoked From the Controllers Node
  2. 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.
  3. 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.

  4. 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.

    Navigating to the View
  5. 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

  1. 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.
  2. 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.

    Index View Displayed in the Browser
  3. 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.
  4. In the Projects window, expand Public.
  5. Right-click the index.html node and choose Delete from the pop-up menu.
  6. In the Projects window, expand the Configuration node and double-click routes.rb to open it in the editor.
  7. Look for the following comment.
      # map.root :controller => "welcome"
            

    Replace the comment with the following code.

      map.root :controller => "item"
            
  8. 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.

    Server Stop Button
  9. Click Run Main Project to start the application in the browser.
  10. 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

Next Steps


>> More NetBeans Ruby Documentation

Companion
Projects:
MySQL Database Server   Open JDK: an Open SourceJDK   GlassFish Community: an Open Source Application Server    Mobile & Embedded Community    Open Solaris   java.net - The Source for Java Technology Collaboration   Virtual Box - full virtualizer  Open ESB - The Open Enterprise Service Bus Powered by