corner imagecorner image
IDEPlatformPluginsDocs & SupportCommunityPartners

NetBeans IDE Ruby Quick Start Tutorial


This tutorial gives you a quick guide to Ruby application development in the NetBeans IDE. The tutorial shows you how to use the IDE's Ruby support to perform some typical application development tasks.

To make this tutorial quick and easy, the tutorial does not work with a database. If you are interested in learning about how to build a Rails database application, see the Creating a Ruby Weblog in 10 Minutes tutorial.

Contents

Content on this page applies to NetBeans IDE 6.9

Requirements

To complete this tutorial, you need the following software and resources:

Software or Resource Version Required
NetBeans IDE Ruby Bundle Version 6.9
Java Development Kit (JDK) Version 6
Rails Framework 2.3.4*

* The NetBeans IDE 6.9 with Ruby and Rails support includes JRuby 1.5 and the Rails 2.3.4 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, the current project is the one that you are performing actions on, such as editing one of its files. If you set a project as the main project, that project remains the current project as long as it is open. The name of the current project appears in the IDE's title bar. The current project is the project that the IDE runs when you click the Run Project button.

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

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:

    • Microsoft Windows, Solaris, and Linux. Double-click the NetBeans desktop icon.
    • Apple Macintosh. 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

    You can quickly access most menu actions by typing the first few characters of the action in the search box that appears on the right side of the main toolbar, as shown in the following figure.

    Accessing actions by using the search box
  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. Right-click the project node in the Projects Window and select Run.

    The IDE displays the output in a window at the bottom of the IDE, as shown next.

    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 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 unit test for a product item class. Next you create the Item class and run the unit test to verify the class. Last, you create a data file to supply the item data, and you edit the main.rb file to display the list. As you develop the code, the steps also introduce editing features.

Create the ItemTest Class

  1. Create a Ruby project, or use the one that you created in the previous section.
  2. In the Projects window, create a unit test by right-clicking the Test Files node and choosing New > Ruby Unit Test from the pop-up menu, as shown in the following figure.

    Choosing New Ruby Test in pop-up menu
  3. Type ItemTest in the Class text box, as shown in the next figure.

    The IDE sets the File Name based on the Class name. The Ruby convention is to use camel case (embedded capitals) to separate words in a class name and the underscore to separate words in a file name.

     New Ruby Test name and location
  4. Ensure that Test Files is selected from the Location drop-down list.

  5. Click Finish.

    The IDE opens the file in the editor.

  6. Replace the contents of the file with the following code.

    $:.unshift File.join(File.dirname(__FILE__),'..','lib')
    
    require 'test/unit'
    require 'item'
    
    class ItemTest < Test::Unit::TestCase
      PRICE = 24.95
      TYPE = "book"
      ID = "BF1"
      def test_string
        assert_equal("Item BF1 is a book: Price $24.95",
          Item.new(ID, TYPE, PRICE).to_s, "Wrong String")
      end
    end
  7. Click the small x in the file's tab to close the file. When the Question dialog box appears, click Save.

Create the Item Class

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

  2. Type Item in the Class text box.

  3. Ensure that Source Files is selected from the Location drop-down list.

  4. Click Finish.

    The IDE creates a file named item.rb and opens the file in the editor.

  5. (Optional) Now that you have established the Item class, you can try out the unit test. Right-click the simple_ruby_application project node and choose Test from the pop-up menu.

    Because you have not yet defined the class, the test fails, as shown in the following figure.

    Ruby Test Results showing failed test

    Note: The Test action runs all the project's unit tests.

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

  9. 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
  10. 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
  11. Type id, :type, :price to complete the statement and press Enter.

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

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

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

    Quick fix tooltip
  15. 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
  16. Select Introduce Constant and press Enter.

    The Introduce Constant dialog box appears.

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

  18. 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
            
  19. Now you can verify whether your class passes the test. Right-click in the source and choose Test File from the pop-up menu.

    The IDE runs the tests in the ItemTest class, and displays the output in the Ruby Test Results window, as shown in the following figure.

    Test passing in the Ruby Test Results window

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. Be careful not to leave any space before the beginning of the text!

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

  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.

    Because the item.rb file is the only possible import that starts with "it," the IDE automatically completes the string with item.

  6. 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
  7. Type print_line and press Enter.

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

  8. To run the project, right-click the project node and select Run.

    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
  9. To practice what you have learned, create another Ruby project. Have the project read and display the entries in a task list.

Next Steps

  • To get started with Ruby on Rails using the IDE, see NetBeans IDE Ruby Rails Quick Start Tutorial.
  • To learn how to use the IDE to build a Rails application based on database tables, see Creating a Ruby Weblog in 10 Minutes .
  • 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.

Additional Sources of Information About Ruby Development