Using the Ruby Development Tools plug-in for Eclipse

来源:百度文库 编辑:神马文学网 时间:2024/04/25 16:21:00

Document options

Print this page

E-mail this page
Rate this page

Help us improve this content
Level: Intermediate
Neal Ford (nealford@nealford.com), Application Architect, ThoughtWorks
11 Oct 2005
This article introduces using the Ruby Development Tools (RDT) plug-in for Eclipse, which allows Eclipse to become a first-rate Ruby development environment. Ruby developers who want to learn how to use the rich infrastructure of the Eclipse community to support their language will benefit, as will Java™ developers who are interested in using Ruby.
Why would any self-respecting Java developer care about Ruby? Ruby is a general-purpose scripting language created 10 years ago in Japan. Contrary to popular belief, it is a pure object-oriented language. Unlike Java technology, Ruby has no scalars, so everything, including integers, are first-class objects. Ruby‘s syntax borrows heavily from Smalltalk, Python, and Ada. Like the Java programming language, Ruby is a single inheritance language, but it offers some advanced features that Java technology does not, such as closures (think anonymous inner classes on steroids) and mix-ins (similar to interfaces, but less tightly bound to the class). Ruby is also highly portable, running on all major operating systems.
Ruby is also red-hot right now. People are starting to use it for the types of applications where it excels. Because it is interpreted and uses dynamic typing, you can do all sorts of magic tricks at run time that are very difficult in Java. One of the surprising capabilities enabled by dynamic typing and expressive syntax is the ability to create domain-specific languages in Ruby that allow you to work at a higher level of abstraction, away from the "raw" syntax of the language. Ruby on Rails is a framework for creating Web applications backed by databases that shows this elegance. Rake, Ruby‘s version of Make and Ant rolled into one, is another example of this powerful use of the language.
The other reason to start playing with Ruby is that all the cool kids are doing it. Many of the people who recognized that Java technology was going to be important back in 1996 (like Glenn Vanderburg, Bruce Tate, and Martin Fowler) are heavily involved in Ruby now. Even if you aren‘t going to change all your development efforts to Ruby, maybe it‘s time you took a look at this language.
One of the main limiting factors to widespread development in Ruby is a good development environment (for those who don‘t want to learn Emacs). The RDT changes that. What better way to experiment with Ruby than in your favorite IDE, Eclipse?


Back to top
Before you can start playing with Ruby, you have to install -- or verify that you have -- the Ruby interpreter and libraries, and the Ruby Development Environment.
Ruby is available for all major platforms -- and some minor ones, as well. In fact, your Linux® or Cygwin distribution may already have it. Go to a command prompt and type ruby -v
If you get a version number, you are ready to go. If not, you need to go grab it. Check out thedistributions for your platform of choice.
If you are running Windows®, the options are even easier. RubyForge, the Ruby-specific equivalent of SourceForge, has a project called the One-Click Ruby Installer, a program that sets up the Ruby environment on Windows (seeResources). It also includes several extra tools, including an IDE called FreeRide, but you can skip most of those in the setup if you are using the RDT.


Back to top
Documentation and other reference materials are crucial when you start to play with a new language. You can get online references to Ruby documentation at the main Ruby Web site, but you will find that the documentation there is a bit outdated (it is for Ruby V1.6, and the current version is 1.8.2). The problem is that the updated docs have not been translated from Japanese yet. However, you can find good up-to-date documentation at Ruby-doc.org. It includes API-level documentation (equivalent to Javadoc), along with some tutorials and books. (SeeResources.)
If you are serious about Ruby development, you should run as fast as you can to get Programming Ruby: The Pragmatic Programmer‘s Guide, by Dave Thomas and Andy Hunt (seeResources). This is the gold-standard introduction to Ruby and a requirement for a Ruby library. While you are getting that book, you can pick up Agile Development with Ruby on Rails, also by Dave Thomas, which is an introduction to Ruby on Rails.
Now that you have a working, documented version of Ruby on your computer, you need RDT (seeResources). This a plug-in for Eclipse that offers many of the features to which you‘ve become accustomed when editing code. RDT is a standard Eclipse plug-in, with features and plug-ins, so you can expand the zip file directly into the Eclipse folder. The paths in the archive take care of the rest.
Now you are ready to create a Ruby project (see Figure 1).

Ruby has much less strict requirements for names and directory structures than Java technology. Creating a project in Ruby really just creates a directory and a .project file (there is no need for the .classpath file because Ruby has no classpath). Another notable difference from Java technology is that the Ruby project wizard does not create explicit src and bin directories. Ruby is interpreted, so there is no output folder. If you have a small project, you can place the Ruby source files in the same folder as the project file. Alternatively, you can create your own directory hierarchy. You will find that Ruby cares much less about this than the Java programming language.
Next, you will want a Ruby source file. There is no specific wizard to create a Ruby source file. There is much less required structure for a Ruby source file than in Java technology, so to create a Ruby file, use the right-click menu on the project to create a new file.

Don‘t forget to add the standard extension of .rb to the file, which is the normal Ruby extension. Creating a Ruby file should open the Ruby perspective.

The Ruby perspective also features an outline view, similar to the one offered by the Java perspective. Like the Java counterpart, it allows you to navigate the elements of the Ruby source file. In Figure 4, the raise_salary_by method is highlighted in both the outline and source view.

Just like other sophisticated plug-ins, RDT also adds customization features within the Window > Preferences dialog. This preferences dialog appears in Figure 5.

The preferences menu item allows you to change syntax highlighting, formatting (the standard indentation in the Ruby world is two spaces, not four, so get ready for some adjustment), and syntax highlighting. It also allows you to customize the editor templates and pick your interpreter.


Back to top
In the Java technology world, we have become accustomed to advanced editor features, which make it difficult to move to other environments that do not offer the same support. One of the features missing from Ruby IDE‘s is Content Assist, offering context-sensitive lookups for identifiers. The RDT editor has Content Assist for Ruby code.

The Content Assist in the RDT editor is less specific than in the Java world because Ruby is dynamically typed. You cannot assign a type to a variable or method return in Ruby. The identifier context determines the type at run time. Ruby uses what is affectionately referred to as "duck typing" -- if it accepts a "quack" message, it must be a duck. While this may seem like a hindrance to those accustomed to strongly typed languages, this loose-type coupling enables some of the more powerful features of the Ruby language. For example, you can write an exception handler in Ruby that is triggered if you call a method that does not exist, and the exception handler can synthesize the method on the fly and turn around to call it. That level of meta-programming is difficult in strongly typed languages.
One of the redeeming features for Content Assist is the special naming conventions Ruby uses for identifiers. For example, in Ruby, all member variables spring into existence upon first use, and are all identified by a @ sign as the first character of the name. If you are looking for member variables using Content Assist, you can start by typing the @ and see just member variables.

The dynamic typing still hinders the context-sensitivity in Ruby. In Figure 7, the only legitimate member variables are the ones that appear just above the method declaration, namely @name, @salary, and @hire_year. The other member variables Content Assist is picking up are from another class, defined later. The RDT editor is not sophisticated enough yet to filter out all syntactically correct, but semantically incorrect entries.


Back to top
One of the key features of an IDE is the ability to run and debug the applications you build from within the same environment. The RDT enables both of these capabilities.
Ruby is an interpreted language, so you must associate an interpreter with your environment before the RDT can run or debug your application. This association resides in the Windows > Preferences dialog under the Ruby heading and the Installed Interpreters entry.

You point the "Location" text field to the bin directory for the Ruby version you are using. The RDT picks up the rest of the needed information. Once you have associated the interpreter, you are ready to run your application.
Running a Ruby application is virtually identical to running a Java application. You create a Run configuration using the Run menu.

When you run the application, the RDT shells out to the Ruby interpreter and runs the application within the console window at the bottom of the Eclipse workspace.

This example shows running a console application, but running other types of applications (like graphical applications) works in the same way.
One of the most critical features required of an IDE is the ability to debug your applications effectively. The Ruby interpreter includes a command-line debugger, but who wants to use a command-line debugger in this age of graphical tools? Fortunately, the Ruby interpreter also broadcasts debugging information over a specific (configurable) port, and tools like the RDT can listen over that port and supply the types of debugging support developers expect.
To debug a Ruby application in the RDT, create a Debug configuration just like the Run configuration created above. You then set a breakpoint by clicking in the gutter in the left-hand margin and launch the application using the debugger. Just as with Java technology, the IDE will ask if you want to switch to the Debug perspective. When you do, you will see something similar to this:

The same level of debugging support found in Java technology appears in the RDT. The upper-left pane shows the current executing thread. The upper-right pane shows the values of variables. Just as in the Java programming language, you can drill into objects to see their underlying member variable values. The middle-left pane shows the source code of the running application, and the middle-right pane shows the outline view -- which works here as in the editor, allowing you to navigate by clicking on an identifier). The bottom of the Debug window shows that the Ruby interpreter broadcasts debugging information on port 1098, and the RDT listens on that port for debugging information.
Debugging support is a key feature of the RDT. Even if you have an editor that has excellent Ruby support, you still must rely on the command-line debugger to debug your applications. Having a fully functional debugger is a huge productivity gain.


Back to top
One of the hardest Ruby characteristics for Java developers to embrace is dynamic typing. If you are accustomed to a strongly typed language, dynamic typing seems like a step toward anarchy. Dynamic typing allows all sorts of advanced meta-programming tricks that are difficult or impossible in a strongly typed language. Of course, you also give up the safety net of the compile-time type checking. Is there a way to get the best of both worlds?
Unit testing should be mandatory for languages, but it is especially critical in dynamic languages. Unit testing reveals much more than mere compilation. In fact, you should change your perspective on the relationship between unit testing and compilation. Recently, at an expert panel at a No Fluff, Just Stuff Software Symposium, Stuart Halloway (of Relevance, LLC), a deep thinker about software development, stated, "In five years, we will view compilation as a really weak form of unit test." Unit testing provides verification that the code does what is expected, not just spell-checking your typing.
Given the importance of unit testing in the Ruby world, you would hope that the RDT makes it easy to run unit tests. It does. Unit testing is included within Ruby, so you do not have to download any additional extensions. The Ruby library includes a TestCase class and the concept of a TestSuite. You create your unit tests like any other Ruby class, subclassing your test from Test::Unit::TestCase. Listing 1 is an example class named Employee.
class Employee def initialize(name, salary, hire_year) @name = name @salary = salary @hire_year = hire_year end attr_reader :name, :salary, :hire_year def raise_salary_by(perc) @salary += (@salary * (perc * 0.01)) end def to_s "Name is #{@name}, salary is #{@salary}, " + "hire year is #{@hire_year}" end end
The corresponding unit test:
require ‘test/unit/testcase‘ require ‘test/unit/autorunner‘ require ‘hr‘ class TestEmployee < Test::Unit::TestCase @@Test_Salary = 2500 def setup @emp = Employee.new("Homer", @@Test_Salary, 2003) end def test_raise_salary @emp.raise_salary_by(10) expected = (@@Test_Salary * 0.10) + @@Test_Salary assert( expected == @emp.salary) end end
To run this unit test, create a Run configuration for the unit test class as a Test::Unit type.

When you run this test, you get the same supporting elements as a Java unit test, including the JUnit-like pane in the lower-left corner.

You can also create TestSuites in Ruby. TestSuites are Ruby classes that define a suite method that returns the TestSuite. The TestSuite consists of the suites defined automatically in each of the TestCases. Listing 3 is a sample TestSuite for a couple of classes.
require ‘test/unit/testsuite‘ require ‘test/unit/ui/tk/testrunner‘ require ‘test/unit/ui/console/testrunner‘ require ‘TestEmployee‘ require ‘TestManager‘ class TestSuite_AllTests def self.suite suite = Test::Unit::TestSuite.new("HR Tests") suite << TestEmployee.suite suite << TestManager.suite return suite end end #Test::Unit::UI::Tk::TestRunner.run(TestSuite_AllTests) Test::Unit::UI::Console::TestRunner.run(TestSuite_AllTests)
Unlike the previous example of running a single TestCase, the suite runs as a stand-alone application. Ruby includes two ways to show the results of the TestSuite. The first, the Console Test Runner, outputs its results at the console. The second, the Tk TestRunner, creates a familiar dialog to show the results of the tests. The Tk TestSuite dialog appears in Figure 14.



Back to top
The current version of the RDT is 0.50. Its developers are hard at work on the next version: 0.60. The improvements slated for the next release include:
Code folding -- Folding can be enabled for classes and methods. Outline view -- More detailed, with support for local variables. RI view -- Use Ruby‘s ri utility from an RDT view. Task tags -- Create tasks for configurable keywords (like TODO, FIXME) in Ruby comments. Editor improvements -- Auto-complete of brackets, parentheses, and single/double quotes; better code-assist. Inspection shortcuts -- Configurable shortcuts for frequently used inspections during a Debug session, like showing all methods of an object, global constants, and so on.
The next version will make better use of the JRuby byte-code compiler. JRuby is a project that allows Ruby code to compile to Java byte code. That means that the next version of the RDT will be easier to incorporate into the Eclipse world, offering even better support.


Back to top
One of the great pieces of advice in the book Pragmatic Programmer: From Journeyman to Master states that you should learn a new programming language every year to keep yourself up to date and let new languages teach you things about the one you use every day. Ruby has finally reached the tipping point of ubiquity, driven partially by the success of the Ruby on Rails project. The time has come to add Ruby to your arsenal of tools. The RDT is a great way to get your feet wet while staying in a home that you already know.


Back to top
Learn
The home of the Ruby language,Ruby-lang.org, is a portal that leads to other helpful Ruby sites and documentation.
Ruby on Rails is an influential Web application framework based on Ruby. This site allows you to download rails and see sample applications.
Rubyforge.org housesOne-Click Ruby Installer, a program that sets up the Ruby environment on Windows.
Find up-to-date Ruby documentation atRuby-doc.org.
Programming Ruby, The Pragmatic Programmer‘s Guide, 2nd Edition, by Dave Thomas, is the seminal guide to the Ruby language. Written in a very readable style, this book is the first book people new to Ruby should add to their bookshelves. One of the great classics of software engineering literature, read this book even if you don‘t care about Ruby.
Agile Development with Rails: A Pragmatic Guide, by Dave Thomas and David Heinemeier Hansson, is the go-to book if you are interested in Rails. This book is the definitive guide to development with Rails.
The Pragmatic Programmer: From Journeyman to Master, by Andrew Hunt and David Thomas, suggests that developers should learn one new language each year.
Glenn Vanderburg is a software intellectual, offering interesting insights and perspectives. He was one of the first to understand and publicize the true potential of Java technology -- writing the first advanced Java books -- and he‘s been a strong supporter of Ruby for years.
Bruce Tate, of Bitter Java and Bitter EJB fame, has also embraced Ruby and the possibilities of transitioning from Java technology to Ruby. He has several books in the works that show how you can transform yourself from a Java person to a Rubyista. Read his "Secrets of lightweight development success" series on developerWorks.
Relevance, LLC is a consulting and training company that specializes in Ruby and Ruby on Rails.
Martin Fowler is one of the most recognized names in software engineering. He understands deep concepts and writes about them with startling clarity. He has been a vocal advocate of Ruby and the kinds of things you can do with Ruby for years, and the rest of the world is just now catching up. He writes about Ruby frequently in his outstanding blog.
developerWorks offers myriadRuby articles and tutorials, including "Debugging Ruby programs 101" and "Automating tasks with Rake."
Visit the developerWorksOpen source zone for extensive how-to information, tools, and project updates to help you develop with open source technologies and use them with IBM‘s products.
Get products and technologies
GetRuby Development Tools, the plug-in for Eclipse that adds Ruby support, including Content Assist, debugging, and unit test support.
Rake, available atRubyforge.org, is Ruby‘s build tool. Rake offers a language for performing builds, offering the best of Make and Ant. It also demonstrates how the flexible syntax of Ruby makes it easy to create highly specific domain-specific languages.
Innovate your next open source development project withIBM trial software, available for download or on DVD.
Discuss
Get involved in the developerWorks community by participating indeveloperWorks blogs.


Back to top



Neal Ford is an application architect at ThoughtWorks, an IT professional services company. Neal designs and develops applications, instructional materials, magazine articles, courseware, video/DVD presentations, and wrote the books Developing with Delphi: Object-Oriented Techniques, JBuilder 3 Unleashed, and Art of Java Web Development. His primary consulting focus is the building of large-scale enterprise applications. He has also been a speaker at developer conferences.


Back to top

Please take a moment to complete this form to help us better serve you.

Did the information help you to achieve your goal?

Yes No Don‘t know


Please provide us with comments to help improve this page:



How useful is the information?
(1 = Not at all,
5 = Extremely useful)

1 2 3 4 5