Thursday Oct 08, 2009

Personal Connections

When I heard about a Aloha on Rails, I jumped on the chance to attend a local conference. Having been to several JavaOne conferences, I knew how helpful they were they were for learning best practices, discovering what people were adopting, and getting a view of what's coming down the pike. I definitely got all of that, but I unexpectedly took away a lot more.

For one, it was my first "local" conference (well it is an airplane ride away, but it still felt local to me). I was happy to find that about half the people I talked to are developers in Hawaii and a lot of business cards were exchanged with the hope that we could all meet again at Aloha on Rails 2.

Second, it was a small conference. After the first day and a nice pau nana party put on by Agathon Group (thanks guys), everyone was starting to look familiar and we were having great discussions. The theme of the conference was talk story, and that definitely was going on both in the conference rooms and outside. Small conferences also mean that the speakers are easily accessible. Here were people that I have been following for years, like Chad Fowler, Obie Fernandez, Charles Nutter, and Yehuda Katz, that I got to meet face-to-face, as well as people I hadn't heard about but are now on my follow list, such as Blythe Dunham, Jim Weirich (have you learned to play Hawaiian Lullabye on your uke yet?), and Desi McAdam, founder of DevChix. I don't know if it is because everyone was a Rails developer (and following the Rails way), the aloha atmosphere, or what, but it really was a nice crowd of people to hang with.

Last, while there was a lot of good info about how to do Rails right and what is the best stuff to use, the bigger take away for me was how important it is to develop personal connections and get involved in communities. That seemed to be the theme spreading through all the talks...how good things happen when you connect with and share with people outside of your daily job tasks. So that is my new mantra...Get Connected. The first thing I did when I returned to work was to join an online community of tech people on the Big Island, and I have already exchanged emails with a couple of people (whoo hoo, I am not alone). Next, I need to get involved with an open source community. It might be something in the cloud, or some Rails project (maybe a cloud one), I don't know. If you have suggestions, pass them on.

So, anyway, I am pretty energized by the small conference experience. If you haven't done one, you gotta try it. And a BIG thanks to Seth for making it happen. Great job.

Thursday Feb 12, 2009

Telling NetBeans IDE Which JDK to Use

A customer has filed a bug about the Generator menu item not working for NetBeans Rails projects if the IDE is using version 6u12 of the Java Development Kit (JDK) software.

Not knowing how to tell the IDE to use a different JDK, the user reinstalled the NetBeans software.

If you don't know already, there is no need to go to such lengths. Here are two ways to tell the IDE which JDK to use.

  • Specify the JDK in the startup command. Modify the command that starts the IDE to include the --jdkhome option pointing to the desired JDK. For example:

    netbeans-install-dir/bin/netbeans.exe --jdkhome "%JAVA_HOME%"

    The above example uses the %JAVA_HOME% environment variable, which is set to C:\\Program Files\\Java\\jdk1.6.0_10, but you can just supply in the path instead. If it has spaces in it, put the path in quotes (that's why the environment variable is in quotes).

  • Specify the desired JDK in the netbeans.conf file. Open the netbeans-install-dir/etc/netbeans.conf file, look for the following option and set it to point to the desired JDK. You might need to unremark the setting.

    netbeans_jdkhome="path-to-jdk"

  • If you are not able to modify the netbeans.conf file because you are sharing the installation or you don't have permission, you can instead create an etc folder in your NetBeans userdir and put a netbeans.conf file in the etc folder. You only need to put in the options that you want to override. For more information see the How do I make my custom startup parameters permanent? FAQ.

Monday Feb 09, 2009

Installing Your Own JRuby to Use With the NetBeans IDE

The Ruby support for NetBeans includes a bundled JRuby installation. This is great for quickly getting started with the IDE, but I recommend that you download and install your own version of JRuby and use that one instead. There are a few reasons for doing so, one of which is that the next time you install a NetBeans version, you will get a new bundled JRuby installation, most likely a different version. If you have added gems to the old bundled JRuby, you will have to reinstall those gems to the new bundled JRuby.

Another reason is when you want to work with more recent JRuby version. For this reason alone, it is good to learn how to install JRuby and register it with the IDE. Below are the steps that I do to add a JRuby installation.

  1. First download JRuby from the JRuby site and install it by following the Getting Started instructions.

    TIP: If you are downloading the 6RC1 version, after you unpack it, rename the directory from jruby-1.1.6RC1 to jruby-1.1.6. For some reason, The GlassFish app server barfs on the RC1 in the path name.

  2. Put JRuby's bin in your environment path. I remember reading some recommendation that if you have both Ruby and JRuby, put JRuby after Ruby in the path. Because I switch out JRuby versions often, I created a JRUBY environment variable that points to the bin directory of the JRuby that I am working with, and I added the JRUBY environment variable to my path. To test it, I type jruby -v on the command line.

  3. Now you can register your new JRuby installation with the NetBeans IDE. Choose Tools > Ruby Platforms from the main menu. Choose Add Platform, and navigate to and select the JRuby executable in the bin directory. If you are on Windows, this is jruby.bat. Click Open.

  4. This step is optional, and I don't suggest it if you are new to Ruby and installing gems. I get tired of having to install the same gems over and over every time I upgrade JRuby, so I create a separate repository (outside of the installation folder) for the gems. If you want to do this, click the Browse button to the right of the Gem Home text box, type the path to your gem repository, and click Open. (If you don't have one yet, use the New Folder button in the dialog box to create it, such as some-ruby-repo-path/jrubygemrepo. When you click Open, it will ask if you want to set up your repository there, click OK.)

    Next click the Add button to the right of the Gem Path text box and add the repository to the gem path.

  5. You will need the debugger gems. Follow the instructions on the NetBeans Ruby Debugger wiki page. Make sure you get the correct versions -- the ones noted on the wiki page. If you opted for a separate gems repository in the previous step, then add --install-dir your-repo-path to the gem install commands.

  6. Next, I install Rails. You can do this from the command line, or from the IDE's Ruby Gems Manager, which is available from the main menu. When you open the Ruby Gems manager, click the Settings tab and select Fetch All Versions so that you have a choice of which version to download. Then click the New Gems tab and click Reload Gems. Select Rails and click Install. You will be asked to select a version. If you want to follow the 6.5 tutorials, be sure to install Rails 2.1.2 or 2.1.0 because you need Rails 2.1.\* for the tutorials. Version 2.1.1 is not compatible with JRuby.

  7. Some other gems you might want to install right away are jruby-openssl, Active Record JDBC Adapter, and the JDBC adapters for the databases that you use. See Using Database Servers With JRuby for more information about the JDBC adapters.

Hopefully, this is complete enough to get you going. Please add comments if you have suggestions or steps to add.

Tuesday Dec 09, 2008

Our NetBeans Ruby Book is Done!

If you have been wondering why this blog has been so quiet for so long, it is because I was working on a NetBeans Ruby book with Brian Leonard. Brian asked me to help him with the book and I am glad that he did. It was a good experience working with Brian and I am happy with how it turned out.

The book is published by Apress and is available in ebook and hard copy here.

In the book we delve into the details of how to use the IDE to develop Ruby and Ruby on Rails projects. If you haven't tried NetBeans IDE 6.5 yet, I am sure you will find the book helpful from start to finish. For those who are upgrading, the book helps you to learn about the new features. Even if you are an experienced NetBeans user, I bet you will find stuff you don't know, especially in the chapters on using the editor and on customizing the IDE.

We got a lot of help from a lot of people along the way. Foremost were the NetBeans Ruby engineers Erno Mononen and Martin Krauskopf who patiently answered every question. Erno was also the book's technical reviewer. Tor Norbye contributed to the editing chapter, and Nick Sieger helped with the chapters about Warbler and JRuby. When it came to GlassFish, we leaned on Arun Gupta and Peter Williams.

I would also like to thank the frequent posters to the users@ruby.netbeans.org alias, such as Bharat, Anthony, and James, who provided a good user perspective and answered my requests for information about best practices.

Last, I want to show appreciation for my managers Sophia and Dave for their support all the way through the process, and for my husband who took over most of my chores without complaint so I could spend my spare time working on the book.

Monday Dec 08, 2008

Fixing the Rails requires RubyGems >= 1.3.1 Error

Many of you who are trying out the NetBeans IDE Ruby support are running into the following error message:

Rails requires RubyGems >= 1.3.1 (you have 1.2.0). Please `gem update --system` and try again.

This is not a NetBeans error message. It is generated by the Rails framework. This error message happens if you upgrade to Rails 2.2.2.

To compound the frustration, it seems that the suggested command gem update --system does not work on all versions of Ruby Gems. When you try the command, you get a message that there is nothing to update. Fortunately, there is a work around.

Here is one way to fix this Rails/Ruby Gems version mismatch. If you have more than one Ruby installation (for example, you have the JRuby that is installed with the IDE and you have a separate MRI Ruby installation), you need to run the command for each installation. Note that the path to the bundled JRuby bin directory is <netbeans-install-dir>/ruby2/jruby-1.1.4/bin.

In the following steps, replace ruby with jruby if you are updating your JRuby installation.

  1. Open a terminal window and change (cd) to the JRuby or Ruby bin directory.

  2. Type ruby -S gem --version

    If the version is 1.3.1, then that installation has already been updated and you are done. Otherwise, continue.

  3. Type ruby -S gem install rubygems-update

  4. Type ruby -S update_rubygems

  5. To ensure that the update happened, type ruby -S gem --version

Thursday Nov 20, 2008

Quick Note about What's New in NetBeans IDE 6.5 Ruby Support

Here are some of the new features that you will find in the 6.5 release of the NetBeans IDE Ruby Support.

  • New Run/Debug Rake Task action and dialog box
  • New Test Runner including Autotest support
  • Support for Warbler instead of Goldspike, so now can WAR up Ruby projects as well as JRuby projects
  • Integrated GlassFish V3 deployment
  • Additional debugging support: exception & conditional breakpoints
  • New options in Settings tab of Gems Manager
  • Mark Occurrences Ctrl-Up and Ctrl-Down
  • Rubinius support
  • Support for script/destroy
  • Ability to set the Rails version at project creation
  • Ability to set editor formatting on a project-by-project basis using the Project Properties dialog box

Friday Aug 15, 2008

Getting Started With NetBeans Ruby 6.5

Now that I have most of the online help done for NetBeans Ruby 6.5, I can start updating the tutorials. I have already started getting comments from customers who are discovering that the 6.1 tutorials don't work with 6.5, so I thought I should quickly blog about known differences. The main reasons these tutorials don't work with 6.1 are: (1) Rails upgrade from 2.0.2 to 2.1 and (2) the addition of the GlassFish server. I am still learning about the 6.5 changes and enhancements, so I probably won't get them all listed here. If you find something that I didn't catch, please add a comment.

Installing and Configuring Ruby Support

The GlassFish V3 Prelude application server is now included with the Ruby bundle. If you are starting from a fresh install, it will be the default server. When you run your Rails apps using the GlassFish server, the URL will be different than if you run with WEBrick or Mongrel. The port is 8080 and you include project name in the URL. (There is an option in the JRuby tab of the server's properties dialog box to Deploy All Rails Applications at Root Context, so if you don't want the project name in the URL you could change that configuration. However, you can have problems if you have more than one Rails application deployed to the server if they have similar routes.).

For the information about Using Database Servers With JRuby, I suggest that you go to wiki.netbeans.org/FaqRailsJRubyDatabaseAccess. If you are using the generic Active Record JDBC adapter and you select the Access Database Using JDBC checkbox, the IDE puts the appropriate driver in the classpath for you, providing that the database server has been registered with the IDE and the IDE knows the driver's location. If you are running the application with the GlassFish server, and you are using SQLite (or a database server that stores its databases in files), you have to edit the database.yml file to specify the full path to the database, such as

database: /usr/local/sqlite/var/rubyweblog_development.sqlite

Now that GlassFish V3 is included, you can run with GlassFish for your development, test, and production environments. The IDE now uses Warbler instead of Goldspike. If you select the Add Rake Targets to Support App Server Deployment, and you don't have the Warbler gem installed, the New Project wizard forces you to go all the way to the last step, where you can click a button to install Warbler.

Getting Started With Ruby and Rails

With Ruby applications, the concept of a "main" project doesn't apply anymore. If you click the Run Project button in the main toolbar, the IDE runs the current project. To see what the current project is, look in the IDE's title bar. I typically right-click the project's node in the Project window and choose Run project, because that way I don't have to think about which of my open projects is current.

If you are using Rails 2.1.0 (The Bundled JRuby comes with Rails 2.1.0), you need to edit the Configuration > initializers > new_rails_defaults.rb file. Find the two lines that start with ActiveRecord::Base and comment them out. Supposedly, in the next Rails release, this code will only be executed if active record is defined, but for now, you have to comment out the lines.

In Step 7 of Create the Model Class, you paste some code into the item.rb file. In that code, replace this line:

DATA_FILE="data.yml"

with this line:

DATA_FILE = RAILS_ROOT + "/data.yml"

The original code won't work when you run in the GlassFish server, because it relied on the server running in the working directory.

In Step 8 of of Run the Application (for the Rails project), use the X button that appears in the left side of the server's tab in the Output window. While there is also an X button in the bottom right for the WEBrick server, this button does not appear for the GlassFish server. On the other hand, the X button is in all the server output windows.

In Step 9 of Run the Application , there is no longer a "main" project for Ruby projects. So, click the Run Project button if the title bar shows that your Rails application is the current project, or right-click the project's node and choose Run.

Creating a Ruby Weblog in 10 Minutes

In the Creating the Database section, you now choose Run/Debug Rake Task, which opens the Rake Runner. Type db:c in the Filter text box to narrow down the list of tasks. Double-click db:create to run that task.

In step 3 of Creating the Database section, you will see that the file name has changed. Instead of using a sequence number prefix (as in 001_create_posts.rb), the Rails script used a timestamp prefix (something like 200808152345453_create_posts.rb). To learn more about why Rails did this, see Brent's blog entry about timestamp based migrations.

As mentioned earlier, when you run the Rails application with the GlassFish app server, the URL uses 8080 as the port and includes the project name, such as http://localhost:8080/rubyweblog/.

In Step 6 of Adding Another Table Column, the code that is generated for Rails 2.1 looks a little different. You can either copy and paste what is provided in the tutorial, and which still works, or you can duplicate the lines as explained in the step and replace both instances of :title with :body, and replace text_field with text_area as shown below.

  <p>
    <%= f.label :body %><br />
    <%= f.text_area :body %>
  </p>

Do the same as above for new.html.erb.

Wednesday Aug 06, 2008

NetBeans Ruby FAQs in Japanese

Masaki Katakai, who is a software engineer working in the software globalization group, has translated the NetBeans Ruby FAQs into Japanese. Check them out at http://wiki.netbeans.org/RubyFAQJa. The globalization group's main task is to provide localized NetBeans for Japanese, Chinese, and Brazilian Portuguese. Masaki is the technical lead of the globalization side and works on Japanese localization.

Monday Jul 21, 2008

Martin talks about Rake Runner, Ruby Debugging, and Other 6.5 Enhancements

As I mentioned a couple of weeks ago, I am researching the new Ruby and Rails features in the upcoming NetBeans IDE 6.5. Last week, Martin Krauskopf and I talked about the work that he is doing. Some of you might know Martin from his earlier work with Jesse Glick on NetBeans Module Development (also known as APISupport) which was great experience for him. Before he joined Sun, Martin says that he "enjoyed a short experience working on the Vim plugin for Eclipse ;)".

One of his most noticeable pieces of work for 6.5 is the new Rake Runner dialog box, which I am finding to be a nice improvement. In addition, Martin has also done an overhaul on the Rake infrastructure, and he worked on providing a pre-generated Rakefile for new projects, which includes tasks such as clean, gem, packages, rdoc, spec, and test (Martin: thanks Dudley Flanders for tips).

On the debugging side, he has released new versions of the fast JRuby debugger and ruby-debug-ide gems, which the 6.5 IDE utilizes to bring support for conditional breakpoints and catchpoints (breakpoint on exception).

You will also see improvements in the Ruby Gems Manager. When you open up the manager, you can now easily switch the platform, without having to wait for the manager to finish fetching the data for the currently selected repository. Martin also added the -a (fetch all versions) and -d (fetch detailed gem description) options for tweaking gems fetching so that it goes a bit faster. If the manager finds that it doesn't have permissions on the repository directory for updating and installing gems, it will now invoke the underlying gem commands using gksu or kdesu, as appropriate (if it finds it).

Two other changes that Martin made were to (1) provide support for Rubinius, an addition to MRI Ruby and JRuby, and (2) Enable you to use the project's Properties dialog box to pass JVM options to JRuby, such as -Djruby.objectspace.enabled=true. Martin is also looking for user situations where something might go wrong and is trying to either make sure that the user gets good messages to help resolve the problem, or have the IDE handle the situation better. His goal is to provide good problem detection capabilities and to provide users with more useful help and clues in such situations. He is focusing on the areas where there are multiple interpreters and multiple Gem Home and Gem Path settings, some with root-writable repositories, as well different VMs with different fast debugging support. He has made several enhancements in this area for 6.5 and will continue working on this for 6.5 and in the next release.

For 6.5, if time permits, he would also like to add support for the Rubinius fast debugger that is being developed by Adam Gardiner, and polish some problems and behaviors of all debuggers generally, since there are still a few remaining issues after the ruby-debug-ide overhaul.

I asked Martin what he does when he isn't working so hard. He likes to spend his free time doing sports such as skiing and biking. He usually spends his vacations with his girlfriend and their friends traveling in his own country (Czech Republic), or around the world, often in the mountains with backpacks. His best vacation was the trip to Himachal Pradesh in the north-west of India.

Tuesday Jul 15, 2008

Two New Ruby Tutorials for NetBeans IDE 6.1

I just published two more NetBeans IDE 6.1 tutorials.

Getting Started With Ruby and Rails is a quick tutorial that shows off many of the NetBeans features.

Using Java Libraries in Rails Applications shows to use the Java API in Rails applications. In this tutorial, you use the FreeTTS speech synthesis Java libraries to enable users to listen to blog posts. I have fun testing this tutorial and listening to the funny sounding man in my computer read my blogs to me. I got quite a bit of help and advice from NetBeans Ruby users for the final bits of code. Thanks for the help guys! I do appreciate it.

Tuesday Jul 08, 2008

Erno Talks About New Rails Features and Customer Involvement

One of the software engineers that I get to work with on the NetBeans Ruby project is Erno Mononen, who works in Prague. Erno works mostly on the NetBeans Ruby IDE, but is also involved in some parts of the Java EE support in the NetBeans IDE. I am finally catching up with the documentation for 6.1 and took some time to talk with Erno about the work that he is doing for the upcoming 6.5 release.

Chris: The new Test Runner UI that you recently added to the 6.5 development version is awesome. Can you tell us about other cool changes that you are making to the next version of Ruby support?

Erno: Thanks! I'll be looking into adding support for Warbler, which offers a more elegant way to create a .war file out of a Rails application than the currently supported GoldSpike plugin. I'd also like to implement a couple of enhancements in the database and server integration areas, such as adding support for additional servers. And last but not least, there is still a lot to do in the test runner -- I've gotten some very good ideas from our users, and would like to address as many of those as possible for 6.5.

Chris:You mention ideas from users. How do users submit ideas to the NetBeans Ruby engineering team?

Erno:There are several different ways to do that. Users can file enhancement requests directly into our issue tracker or they can send their ideas to the dev@ruby.netbeans.org or users@ruby.netbeans.org mailing lists, where they can be discussed with the community. Furthermore, most of the developers in the Ruby team have blogs that are open for comments. Lastly, we welcome anyone to come to have a chat if you see us around at conferences or anywhere else. Feedback is always appreciated.

Chris: Can you give examples of user suggestions that you have incorporated into the product?

Erno: I think the new test runner serves as a good example both of a user requested new feature and smaller enhancement. It was our users who requested this in the first place, so the test runner as a whole is a user requested feature that has been incorporated into the product. In addition, since its incorporation our users have been active in filing bugs and enhancements for it. For example, the error badges for failing tests in the test tree view of the runner were suggested by a user.

Chris: Can you talk about some of the 6.5 features that you think Ruby programmers will look forward to seeing?

Erno: Hopefully the new test runner will be one of those features :\^) There are quite a few other things as well that I think our users may find of interest, to mention a few of them:

  • The new Rake task runner, which Martin Krauskopf implemented, makes running rake tasks much more convenient
  • Client side JavaScript debugging should be useful to many Rails developers
  • The Quick Search feature offers fast access to all the actions registered in the IDE

In addition there are a lot of improvements in JavaScript, Ruby, and CSS editing, and naturally a bunch of bug fixes in all areas.

Chris: So what do you do when you are not working on the IDE?

Erno: I spend most of my free time with my wife and son, but when I have some time just for myself, I can usually be seen either doing various sports, reading books, or playing the guitar.

Chris: Thanks Erno, I look forward to writing about the new NetBeans Ruby features for 6.5.

Notes: You can download Milestone 1 (a pre-beta version) of NetBeans IDE 6.5 from www.netbeans.org. The Ruby Trails web page has links to Erno's blog as well as the other engineers who work on the NetBeans Ruby IDE. The NetBeans Ruby Wiki page has links to the most recent entries of all these blogs. Also, you can view the NetBeans Ruby mailing lists at Nabble.

Friday Jun 20, 2008

Using the IRB in the NetBeans IDE

Accessing the IRB Console from the IDE

The Ruby support in the NetBeans 6.1 IDE includes the Interactive Ruby (IRB) Console. To open the console, choose Window > Other > Ruby Shell from the main menu. The console opens in the bottom window.

The IRB console

The interpreter that is used by the console depends on the main project's Ruby Platform setting (the bold project node in the Projects window is the main project). To see the Ruby Platform setting, right-click on project's node and choose Properties. If your project is a Ruby project, select Run in the Categories pane to see the Ruby Platform setting. You can switch to a different platform, if you want.

The tab for the IRB console window indicates which the interpreter it is using. In the above screenshot, you can see that the IDE is using the Built-In JRuby platform.

To exit from the IRB console, type exit or quit, and close the window.

Using Gems in the IRB Console

Before you can use gems in the IRB, you have to load RubyGems. Most platforms take care of this for you. For those that do not, such as the built-in JRuby platform, you must load it yourself. If you do not load RubyGems, you will see an error similar to the following output.

>> require 'renum'
  LoadError: no such file to load -- renum
  from (irb):2:in `require'
  from (irb):2:in `signal_status'

The quickest way load RubyGems is to type the following statement in the console.

>> require 'rubygems'

If you do not want to type that every time you open an IRB console, you can add -rubygems to the Ruby Options text box in the project's Properties dialog box.

Setting -rubygems in the Properties dialog box

Using .irbrc Files for Common Settings

Another way to load RubyGems every time you open the console, is to add or copy over an .irbrc file to the project's top level folder and add require 'rubygems' to that file. To create an .irbrc file, right-click the project node and choose New > Other from the pop-up menu. Select Other in the Categories pane, select Empty File in the File Types pane, and click Next. Name the file .irbrc and click Finish.

If you have IRB settings that you would like applied to all your projects, such as loading RubyGems, you can put the settings in an .irbrc file in your home directory. In order to get the IDE to read this file when opening the IRB console, you must create a HOME system environment variable (be sure to make it all capital letters) that provides the path to your home directory, and restart the IDE.

Note that you will not see the .irbrc file in the Projects window or the Files window. To learn how to configure the IDE so that you can see this file, see MRHAKI's blog that shows how.

Using the JRuby IRB Console

The IDE also offers support for the JRuby IRB console. With this console, you get code completion, as shown below. You can type the first few characters and press Tab to see a list of suggestions.

JRuby IRB console

The JRuby IRB console also has a history feature. Pressing the Up-Arrow key scrolls through through the command history and pressing the Down-Arrow key scrolls back. You can press Return to re-execute a command.

To enable the JRuby IRB console, add the following flag to your NetBeans IDE startup command or add it to the netbeans_default_options entry in the netbeans-install-dir/etc/netbeans.conf file, and restart the IDE. One problem with this option, is that you get the JRuby IRB console, regardless of which platform your project is using.

-J-Dirb.jruby=true

Tuesday Jun 10, 2008

My Rails Learning Path: Flash Pitfalls

Makalawena Maize

For the past few weeks, I have been working on writing the NetBeans IDE 6.1/Rails 2.0 version of the Building Relationships Between Models tutorial. The NetBeans Ruby community provided helpful guidance, especially Florian Gilcher, who spent a lot of time shaping up the code and teaching me about best practices. Florian moderates the Rails part of Rubyforen.

The first input I got from Florian was actually about the Rails 1.2 version of the tutorial. In this tutorial, they used the flash to pass the post's id from the show action to the show template and from the show template to post_comment action.

Florian pointed out that using the flash to store state information can cause two severe bugs:

  • Session Time Out Bug. A session is volatile and thus gets erased after a certain amount of time, typically 15 minutes after the last client request. Should a user get a phone call in the middle of writing a comment, the session could be invalidated, creating a new one. When the user submits the comment, the flash is empty and he gets a 500 status. Not good!.

  • Multiple Request Bug. The flash holds for one unspecified request. If the browser fires off another request, the flash is emptied. Thus a user switching between writing a comment and reading posts on other message boards runs into the same problem as above.

I have the feeling that several of the lab participants at our JavaOne hands-on-lab ran into these exact problems, as they were using the same browser to read the lab steps and run the application. I had not run into these problems when testing the lab or the original tutorial. As Florian pointed out, "The bad thing about both bugs is that they almost never appear in testing environments. I would never sit before my PC writing plain text for 15 minutes, and explain my boss that I was testing ;)."

Instead of using the flash, you can simply add the the id in the call to form_tag (form_tag :action => 'post_comment', :id => @post). This maps to /blog/post_comment/id, which matches the pattern declared by the map.connect ':controller/:action/:id' mapping in routes.rb. An alternative is to pass it in a hidden field. One problem with these solutions is that the data can be tampered with, so you need to make your application able to cope with that. As Florian said, "If the user wants to play madman, he should only be able do this with data he actually is allowed to edit."

So, lesson learned! Fortunately, the NetBeans Ruby 6.1 tutorials use RESTful resources, and thus eliminate this bad practice altogether.

Friday Jun 06, 2008

Rails RESTful Resources Tutorial

Today, we published an updated version of the Building a Relationship Between Two Models tutorial. This update takes the RESTful approach to working with has_many relationships, in this case the relationship between a post (the parent) and its comments (the children). REST, which is an acronym for representational state transfer, is an architecture style for hypermedia, such as web applications. By using this architecture, you end up with a simple, uniform way to set up routing for your create-read-update-delete (CRUD) applications, which typically perform the following actions for a resource:

  • List (Index)
  • Create
  • New
  • Show
  • Edit
  • Update
  • Destroy

With RESTful routing, you can use a combination of four HTTP methods (GET, POST, PUT, and DELETE) and four patterns (/controller-name, /controller-name/:id, /controller-name/:id/edit, and /controller-name/new) to formulate the URLs that map to the above actions. For example, for the post resource, you can use the following URLs and HTTP methods:

  • List. /posts + GET
  • Create. /posts + POST
  • New. /posts/new + GET
  • Show. /posts/:id + GET
  • Edit. /posts/:id/edit + GET
  • Update. /posts/:id/ + PUT
  • Destroy. /posts/:id + DELETE

The Rails support for RESTful routing makes this all very easy. When you add a resource to your Rails application, the framework automatically adds to the routes.rb file a map.resource method call that generates the appropriate route mappings to the seven actions, and also creates numerous helper methods for generating paths and urls in string and hash format. Basically, all you have to remember are four substrings:

  • collection, such as posts, for list (index) and create
  • object, such as post, for show, edit, and destroy
  • new_object, such as new_post, for new
  • edit_object, such as edit_post, for edit

For example, to generate the path to invoke the create action, you use new_post_path. To generate the path to invoke the edit action, you use edit_post_path(:id).

In the scenario in the tutorial, where there is a parent-child relationship, you use the Rails nested resources support, which ensures that the comment resources are always accessed in relationship to a post. For example, to generate the path to the create action for comments, you use post_comments_path(:post_id), which generates the URL /posts/:post_id/comments.

The tutorial is a nice way to quickly see RESTful routing in action. If you are interested in learning more about this topic, the tutorial lists several resources that provide in depth explanations of REST architecture and Rails support for this methodology.

Note: I should point out that REST architecture is not simply about URLs and routing. It is a set of constraints that "when applied as a whole, emphasizes scalability of component interactions, generality of interfaces, independent deployment of components, and intermediary components to reduce interaction latency, enforce security, and encapsulate legacy systems." [Roy Fielding, Architectural Styles and the Design of Network-based Software Architectures, Chapter 5, 2000].

Tuesday Apr 08, 2008

See You at JavaOne 2008

This year, Brian Leonard, and I (diva #2) are putting on the Developing (J)Ruby on Rails Applications with the NetBeans™ IDE hands-on lab at JavaOne. If you haven't tried developing a web application using Ruby on Rails, this is a good opportunity to get your feet wet. For those of you who are familiar with Ruby but haven't tried it in the IDE, you will also find this lab helpful. In this lab, you build the classic Ruby web log, you access the FreeTTS Java API to speach-enable the application, and you deploy the application to the GlassFish application server.

Speaking of JavaOne, in last year's hands-on-lab, one of the exercises was to use Dynamic Faces to build a chat room application. This section has been turned into the Building an Ajax Chat Room with the Ajax Transaction Dynamic Faces Component tutorial which is available from the NetBeans Web Application Learning Trail.

About the picture. Right behind me is flowing lava. To be able to walk right up to 1200 degree Celsius lava flow was an awesome experience. Fortunately, because the lava contains a large amount of glass, the lava flows very slowly.

Wednesday Mar 26, 2008

New Ruby Developer Resource Center

The Ruby Developer Resource Center at developers.sun.com is live. Just learning or already deploying? Get downloads, docs, news feeds, blogs, screencasts, and learning trails to help you build applications using Ruby, JRuby, and Ruby-on-Rails.

Friday Feb 29, 2008

NetBeans 6.1 Draft: Creating a Rails 2.0 Weblog in 10 Minutes

April 8, 2008 Update: The final version of this tutorial is available at http://www.netbeans.org/kb/61/ruby/rapid-ruby-weblog.html.

This is an early draft of a NetBeans IDE 6.1 tutorial in which you use the Ruby support in the NetBeans IDE to create and run a simple Rails 2.0 web application. This tutorial is an update of an earlier blog, which was written for NetBeans IDE 6.0. A final version of this tutorial will be published at www.netbeans.org when final NetBeans IDE 6.1 is released.

Tutorial Requirements

This tutorial requires the following technologies and resources.

Creating the Ruby on Rails Project

You begin by creating a Ruby on Rails project. By default, the application is created in a directory structure that conforms to the Ruby on Rails project conventions for applications.

  1. In the NetBeans IDE, choose File > New Project.

  2. Select Ruby from the Categories list and Ruby on Rails Application from the Projects list. Click Next.

  3. Type rubyweblog in the Project Name text box. Accept all the other default settings on this page.

  4. Click Next.

  5. Select Specify Database Information Directly.

  6. Leave the Database Name text box blank, the IDE will create default development, test, and production database names based on the project name.

  7. Type root in the User Name text box.

  8. If the root user requires a password, type the password in the Password text box.

  9. Click Finish to create the new project.

    The IDE creates the project directory with the same name as your project and opens the database.yml file in the editing area. Notice that the default database name for the development configuration is rubyweblog_development.

  10. Click the small x button in the database.yml tab to close the file.

Creating the Scaffold

This weblog application is built around the Post model, which stores instances of blog posts. Here you use the Rails scaffold generator to create the model and its controller, as well as the index (list), show, new, and edit views.

The generator also creates a migration file for creating the model's database table, and creates unit test and fixture stubs for writing model tests. Last, the generator adds the map.resources :posts declaration to the routes.rb file to create named routes that are mapped to the URL paths for the controller actions.

  1. In the Projects window, right-click the rubyweblog project node and choose Generate.

  2. In the Rails Generator dialog box, select scaffold from the Generate drop-down list. Make sure that you select scaffold, and not use the default selected value (controller).

  3. Type Post in the Model Name text box.

  4. Type title:string in the Attribute Pairs text box, as shown in the following figure, and click OK.

    The Output window lists the files that the scaffold generator creates and updates.

Creating the Database

In this section, you use a Rake task to create the rubyweblog_development database. Then you use the 001_create_posts.rb migration file to add the Posts table to the database.

  1. In the Projects window, right-click the rubyweblog project node, and choose Run Rake Task > db > create.

    Rake creates the MySQL database for the development configuration in the database.yml file.

  2. In the Projects window, expand Database Migrations and expand migrate.

  3. Double-click the 001_create_posts.rb node to open the file in the editing area.

    The file opens to show the self.up method, which creates a table called posts, and the self.down method, which tears the posts table down, as shown in the following code sample.

    Code Sample 1: Code for 001_create_posts.rb
    class CreatePosts < ActiveRecord::Migration
      def self.up
        create_table :posts do |t|
          t.string :title
    
          t.timestamps
        end
      end
    
      def self.down
        drop_table :posts
      end
    end

    Note that the create_table method adds an id column by default, and that the timestamps method adds the created_at and updated_at columns to the database table.

  4. In the Projects window, right-click the rubyweblog node and choose Migrate Database > To Current Version.

    This action updates the the database to include the posts table. The Output window indicates when the migration is complete.

Running the Application

Now test the application.
  1. In the Projects window, expand the Configuration node and double-click routes.rb to open it in the editor. Find the comment:

    # map.root :controller => "welcome"
    	
  2. Add the following line under the comment.
    map.root :controller => "posts"
    	
  3. In the Projects window, expand the Public node, right-click index.html and choose Delete.

    The index.html page displays a default Welcome page, which is not what you want. By deleting index.html, Rails looks in routes.rb to figure out what page to display.

  4. Choose File > Save All from the main menu.

  5. Click the Run Main Project button in the toolbar.

    This action starts the WEBrick server, which is part of the Ruby on Rails framework, and launches the web browser.

    If you are using a server other than WEBrick, you might need to enter http://localhost:3000 in the browser's address text box and press Enter.

  6. Click the New post link to display the second page of the application.

  7. Enter a title and click Create.

  8. Click the Back link to return to the list of posts.

Doing More: Adding Another Table Column

Here you add a body column to posts table to hold the text for each blog entry.

  1. Right-click the Database Migrations node and choose Generate. In the Rails Generator dialog box, type AddBodyToPost body:text in the Arguments text box and click OK.

    The IDE creates the versioned migration script 002_add_body_to_post.rb. The file opens to show the self.up method, which adds a body column, and the self.down method, which removes the column, as shown in the following code sample. Notice how the generated code extracted the table name from the first argument AddBodyToPost.

    Code Sample 2: Code for 002_add_body_to_post.rb
    class AddBodyToPost < ActiveRecord::Migration
      def self.up
        add_column :posts, :body, :text
      end
    
      def self.down
        remove_column :posts, :body
      end
    end

  2. Right-click the rubyweblog node and choose Migrate Database > To Current Version.

    Alternatively, right-click in the source file and choose Run File from the pop-up menu.

  3. In the Projects window, expand Views and expand posts.

  4. Double-click edit.html.erb to open the file in the editing area.

  5. Add the statements shown in bold in the following code sample.

    Alternatively, place the cursor before the <p> tag for the Title and drag the mouse to the position after the paragraph's ending </p> tag, then press Ctrl+Shift+Down Arrow to duplicate the lines. Replace Title with Body and replace f.text_field :title with f.text_area :body.

    Code Sample 3: Adding the Body to the Edit View
    <h1>Editing post</h1>
    
    <%= error_messages_for :post %>
    
    <% form_for(@post) do |f| %>
      <p>
        <b>Title</b><br />
        <%= f.text_field :title %>
      </p>
    
      <p>
        <b>Body</b><br />
        <%= f.text_area :body %>
      </p>
    
      <p>
        <%= f.submit "Update" %>
      </p>
    <% end %>
    
    <%= link_to 'Show', @post %> |
    <%= link_to 'Back', posts_path %>


  6. Double-click new.html.erb to open the file in the editing area.

  7. Add the statements shown in bold in the following code sample. Alternatively, use Ctrl+Shift+Down Arrow to duplicate the Title paragraph and edit the duplicated code as described in Step 5.

    Code Sample 4: Adding the Body to the New View
    <h1>New post</h1>
    
    <%= error_messages_for :post %>
    
    <% form_for(@post) do |f| %>
      <p>
        <b>Title</b><br />
        <%= f.text_field :title %>
      </p>
    
      <p>
        <b>Body</b><br />
        <%= f.text_area :body %>
      </p>
    	
      <p>
        <%= f.submit "Create" %>
      </p>
    <% end %>
    
    <%= link_to 'Back', posts_path %>


  8. Double-click show.html.erb to open the file in the editing area.

  9. Add the statements shown in bold in the following code sample. Alternatively, use Ctrl+Shift+Down Arrow to duplicate the Title paragraph as described in Step 5, change Title: to Body:, and change @post.title to @post.body.

    Code Sample 5: Adding the Body to the Show View
    <p>
      <b>Title:</b>
      <%=h @post.title %>
    </p>
    
    <p>
      <b>Body:</b>
      <%=h @post.body %>
    </p>
    
    <%= link_to 'Edit', edit_post_path(@post) %> |
    <%= link_to 'Back', posts_path %>


  10. Choose File > Save All.

  11. Return to the browser and click the New Post link to see how Ruby recognizes the new body column.

  12. Create a few more blog entries.

Doing More: Validating Input

Here, you add code to the Post class to ensure that the users provide values for both the title and the body fields.

  1. In the Projects window, expand the Models node and double-click post.rb to open the file in the editor.

  2. Open up a line inside the Class definition, type vp, then press Tab.

    The IDE replaces the vp trigger with the following code template.
    validates_presence_of :attribute
  3. Type title, :body. The code should look like the following statement.
    validates_presence_of :title, :body
  4. Run the application, click New Post, and click Create.

    The application now reports that the title and body cannot be blank.

Doing More: Making the List Look More Like a Blog

  1. Expand Views > posts and open index.html.erb, which is used to show the list of blog entries. Delete the <h1> and <table> tags and replace them with the following code that is shown in bold.

    Code Sample 6: Code for index.html.erb
    <h1>The Ruby Blog</h1>
    
    <% @posts.each do |post|  %>
      <h2><%=h post.title %></h2>
      <p><%=h post.body %></p>
      <small><%= link_to 'Permalink', post %></small>
      <hr>
    <% end %>
    
    <br />
    
    <%= link_to 'New post', new_post_path %>
    
    

    For each instance of a post action, this code produces a title, body, and Permalink.

    Notice that the second parameter for link_to is post. You might remember that when you generated the scaffold, the generator added a map.resources :posts declaration to the routes.rb. The resources method generates named routes for the Post model, one of which is post. The post named route produces the same result as passing :action => 'show', :id => post to the link_to method. The post id is passed in the URL. When you click the Permalink link, look at the URL in the address bar. You should see a URL similar to http://localhost:3000/posts/1.

    To see all the named routes for a project, right-click the rubyweblog project node and choose Run Rake Task > routes. The Output window shows the route list. The first column shows the named route, the second and third columns show the HTTP verb and URL that are passed in the request, and the last column shows the controller and action that will be called. To learn more about using named routes see the Rails API for the ActionController:Resources class.

  2. Save the changes and run the application to see the new interface for the Post model.

  3. To display the blog with the most recent entry first, edit the code that you just added to reverse the sort order by adding a call to the .reverse method, as shown below.

    <% @posts.reverse.each do |post| %>
    	  
  4. Save the file and refresh your browser to see the list displayed in reverse order.

Friday Dec 14, 2007

Five-Minute Ruby on Rails jMaki Tutorial

If you have installed the NetBeans IDE support for Ruby and you are interested in integrating jMaki in your Ruby on Rails projects, here is a five-minute tutorial that will get you started. In this tutorial, you add a Yahoo data table to a Ruby on Rails view. (If you have not yet installed the NetBeans IDE 6.0 or if you need to add Ruby support to your NetBeans IDE, learn how to here.)


  1. If you haven't installed the jMaki plugin for the NetBeans IDE, it takes just a minute. Select Tools > Plugins from the main menu, select jMaki Ajax Support, click Install and follow the instructions.

  2. Follow the steps in the "Working With Ruby on Rails Files" section in the Getting Started With Ruby and Rails. This should take just a few minutes as no database is involved. Finish all the steps up to but not including the "Practicing What You Have Learned" subsection. It is important that you add the routing code (Code Sample 10) to the routes.rb file and delete the Public > index.html file.

    Note: If you already have done these sections, but added the jMaki plugin after you created the project, you need to create a new project in order to have jMaki included.

  3. Edit the Views > item > index.rhtml file.

  4. Remove the <table> including the nested <tr> and <td> tags. You will replace this HTML table with the Yahoo Data Table.

  5. Choose Window > Palette from the main menu to view the Palette window.

  6. Expand the jMaki Yahoo section in the Palette, then drag and drop the Data Table onto the index.rhtml.

  7. Replace the jmaki_widget tag with the following code:

    <%= jmaki_widget 'yahoo.dataTable',
    :value =>
    {:columns => [
         { :label => 'Id', :id => 'id'},
         { :label =>'Type', :id => 'type'},
         { :label => 'Price', :id => 'price'},
         ],
      :rows => @items
      }
    -%>
    


  8. Click the small x button in the bottom right corner of the IDE to stop the WEBrick server.

  9. Click the Run Main Project button and the browser should display a nice Yahoo table that contains the item data.

Tuesday Dec 04, 2007

How Do You Ruby?

During your daily use of the NetBeans Ruby support, you are constantly figuring out how to best use the language and the IDE to help you get your job done. Hopefully, the tutorials and articles help you towards your goals, but one size does not fit all. You all have diverse perspectives of the product as you implement your different use cases and scenarios. In addition, you bring with you different sets of habits, mental models, processes, and standards.

As you work with the product, you gain valuable nuggets of information that would be of benefit to others who run into the same situations. The NetBeans Ruby community wiki provides the means to share that knowledge.

You might think that you have to be a subject matter expert before you can contribute, but that is far from true. Often, people who are new to using the NetBeans Ruby support are the perfect teachers for other beginners. You can understand and emphasize with them, and you are probably encountering the same bumps, hurdles, and misunderstandings. Or maybe you are just one step ahead and can help others from making the same mistakes. Also, the act of writing might make your own understanding all that more concrete.

There are many ways in which you can be involved in the NetBeans Ruby community.

  • Users Alias. The users@ruby.netbeans.org email alias is a quick and easy way ask questions and help out others. An added advantage is that the developers are listening and many improvements have been made to the product because people took the time to write their issues and wishes. Often times, during the act of describing your problem concisely, you get the big Aha! that makes the answer obvious. In that case, since you have already written up the problem, you might as well share your problem and solution with the community.

  • FAQs. The FAQ is composed of easy to create and edit wiki pages. The users alias is a good place to look up solutions, but even better is when someone takes the time to summarize a long thread from the users alias into one page of essential information. Another good use for FAQs is to share gotchas and tips.

  • Blogs, Tutorials, and Articles. If you blog about NetBeans Ruby support, notify the users alias so we can link to you. If you want to write a tutorial or article, get in touch with the NetBeans Community Docs Contribution Coordinator Amit Kumar Saha (See Community Docs for instructions). Also let us know, so we can link to your doc from the Ruby Documentation wiki page. We will also be glad to help you with reviews and such.

  • Submit Code. The Ruby Participation wiki page tells how to join the development effort. The Ruby Code Ideas wiki page lists possible projects to work on -- both large and small. Two other ways to contribute are to submit Ruby hints and quick fixes (see Writing New Ruby Hints) and provide suggestions for Ruby code templates.

So, how do you Ruby? Got a nugget to share? We would love to hear from you.

Friday Nov 30, 2007

The NetBeans Ruby Screencast Library

Recently we posted a list of tutorials to help you get started with NetBeans Ruby and Rails. Another way to get started is by watching the NetBeans Ruby screencasts, starring Tor Norbye and Roman Strobl, and produced by Cindy Church. These screencasts provide an overview of the features of NetBeans Ruby, including the Ruby Editor and Debugger, and also provide scenarios for creating Ruby and Rails applications. Sit back, relax, and enjoy.

Creating Ruby and Rails Applications

Using the Ruby Editor

Testing and Debugging

Tuesday Nov 27, 2007

My Ruby Learning Path: Constructing the Constructor

When I started learning Ruby, all of the code samples that I looked at used positional arguments in the constructor, such as with the following code:

  def initialize(id, type, price)
    @id, @type, @price = id, type, price
  end

By positional arguments, I mean that the first argument must pass the id, the second must pass type, and the third must pass price. Having worked with C and Java, this feels very familiar, and so that is how I did it in my own code. However, when I posted my code samples to the dev@ruby.netbeans.org alias, a few developers suggested that I use a hash, like in the following code.


  def initialize(attributes)
    @id = attributes['id']
    @type = attributes['type']
    @price = attributes['price'].to_f
  end

I can see some advantages of using a hash instead of requiring arguments in a certain order. For one, with positional arguments, there is the possibility of passing the values in the wrong order. Another advantage of a hash is that if you add more attributes to a class, the constructor's signature does not change.

There was a bit of a debate about which version to use. Some developers like the constructor with positional arguments because it clearly documents the intent of the class. Others feel that keyword arguments, along with RDoc, make the code more clear than depending on argument ordering to convey meaning. Comparing the two types of method invocations, I have to agree that the hash seems easier to read.

  Item.new 'id' => 'ABC', type' => 'book',  'price' => 17

  Item.new 'ABC', 'book', 23

How about you? What are your preferences? Do you carry it even further? Would you ever consider doing something like this?


  def initialize(&block)
    instance_eval &block
  end

  item = Item.new do
    self.id = 'ABC'
    ...
  end

Do you know of scenarios where it might be appropriate to use code like this?

  def initialize(attributes)
    @attributes = attributes.with_indifferent_access
  end
 
  def method_missing(symbol, \*args)
    @attributes[symbol] ? @attributes[symbol] : super
  end

Charles Nutter has blogged about how to extend Class with a field-initializing 'new' method. Jay Fields posted in his blog code forcreating constructors that can take either positional arguments or a hash. For someone starting out with Ruby, I find these latter methods a bit uncomfortable, but it does save a bit of finger work. What do you think?

Monday Nov 26, 2007

Getting Started With NetBeans Ruby and Rails

Do you need help getting started with NetBeans Ruby? If so, we have three learning trails to get you going. Our first trail gives you a whirlwind tour of the NetBeans Ruby and Ruby on Rails environment. The second trail provides the nuts and bolts for creating a basic Ruby on Rails application. The third trail is an all-in-one lesson for working with Ruby and Java applications. You can start at whatever trail best meets your needs.

Trail 1: Getting Started

Trail 2: Creating a Ruby on Rails Application

Trail 3: Integrating Ruby and Java Development

Tuesday Nov 13, 2007

Getting Your Feet Wet With Java in JRuby

If you haven't tried calling Java classes from a JRuby application yet, here is a simple code snippet to get you started. Paste the following code into the Ruby shell (JRuby IRB), press Enter, and a small desktop app opens (To open the Ruby shell in the NetBeans IDE, choose Ruby > Other > Ruby Shell (IRB) from the main menu). This code is an updated version of an example in the JRuby and the Java Platform article.

Note: A current known bug causes the JRuby IRB to report an ExitSecurityException, this bug does not affect the output.

Code Sample: Using Java Classes in the IRB Console
include Java

import javax.swing.JFrame
import javax.swing.JLabel
import javax.swing.JPanel
import javax.swing.JButton
import java.awt.BorderLayout

frame = JFrame.new
panel = JPanel.new
panel.layout = BorderLayout.new
panel.background = java.awt.Color::white
frame.get_content_pane.add(panel)
frame.default_close_operation = JFrame::EXIT_ON_CLOSE
button = JButton.new "Click Me"
text = JLabel.new "I'm a Simple Program"

panel.add(BorderLayout::CENTER, text)
panel.add(BorderLayout::SOUTH, button)

class Click
    include java.awt.event.ActionListener

    def initialize(button, text)
        @button, @text = button, text
        @click_me_mode = true
    end

    def actionPerformed(event)
        source = event.source
        if (source == @button)
            if (@click_me_mode)
                @text.text = "Button Clicked"
                @button.text = "Click Again"
                @click_me_mode = false
            else
                @text.text = "I'm a Simple Program"
                @button.text = "Click Me"
                @click_me_mode = true
            end
        end
    end
end

button.add_action_listener(Click.new(button, text))
frame.title = "Example"
frame.pack
frame.visible = true 

The IRB is a nice way to test out your code. However, with the NetBeans IDE, it is just as easy to test out code in a scratch program. To see what I mean, right-click in the NetBeans Projects window and choose New > Project. In the New Project wizard, select Ruby in the Categories pane, select Ruby Application in the Projects pane, and click Next. Name the project Scratch (or whatever you want) and click Finish. The main.rb file opens in the editor.

Replace the contents of the main.rb file with the code sample. Then click the Run Main Project button in the main toolbar (the green arrow) to run the application.

As you can see by the following screenshot, the advantage of testing your code in a scratch project as opposed to using the IRB is that you get syntax coloring and all the other wonderful NetBeans Ruby editing features.

To learn about the editing features, see the NetBeans Ruby Editing wiki page, or look at Tor's screenshot of the week entries, such as Ruby Screenshot of the Week #18: Errors and Snippets (as of today, he is up to screenshot #23). We are also working on a getting started guide that will cover some of the editing features. Last, you can watch Roman's Editing screencast.

There are a couple of FAQs that you might find helpful

  1. How to Call Java From Ruby
  2. How Can I Access Java From the JRuby IRB?

You also might want to check out the Swing with JRuby: Developing a Desktop Application with the JRuby and Java Swing APIs tutorial that was written by Sun campus ambassador Teera Kanokkanjanarat.

Wednesday Nov 07, 2007

NetBeans Ruby Shortcuts

The other day, Tor Norbye sent us an email listing some NetBeans Ruby navigation shortcuts, which we thought we'd highlight in the blog. We did a little further research on the subject and also list here some favorite user shortcuts that we undercovered.

(For a complete list of NetBeans Ruby Keyboard Shortcuts, see Ruby Shortcuts).

Navigation Shortcuts

Navigation is important - jumping between files and their tests, or between Rails actions and views. Here are some navigation shortcuts:

  • If you're in a controller file, and realize you need to modify its corresponding view, press Ctrl-Shift-A (Command-Shift-A on the Mac) to jump to it. Press again to go in the opposite direction.
  • Similarly, if you're in a Rails controller file (for example) and want to go edit its unit test, hit Ctrl-Shift-T (Command-Shift-T on the Mac) to jump to it - and again to jump back.

User Favorite Shortcuts

Here are some more frequently used shortcuts.

Action Shortcut Mac Shortcut
Show code completion alternatives Ctrl-Space. If Ctrl-Space does not work for your language, try using Ctrl-\\ Ctrl-Space
Open File by name prefix (not path) Alt-Shift-O Ctrl-Shift-O
Show name of current parameter (when editing an argument list for a method call) Ctrl-P Command-P
Format Code Alt-Shift-F Ctrl-Shift-F
Reformat the current comment paragraph Ctrl-Shift-P Command-Shift-P
Jump to matching parenthesis / brace / bracket, or other matching Ctrl-[ Command-[
Show Documentation Ctrl-Shift-Space Command-Shift-Space

NetBeans Shortcuts

You can download a shortcut card that lists the highlights of the NetBeans IDE 6.0 keyboard shortcuts and code templates. In the NetBeans IDE, choose Help > Keyboard Shortcuts Card from the main menu. Similarly, you can view the shortcuts online from the NetBeans IDE 6.0 Keyboard Shortcuts Specification.

Friday Nov 02, 2007

Confessions of a NetBeans Ruby User

Teera Kanokkanjanarat is a Sun campus ambassador who recently contributed the tutorial Swing with JRuby: Developing a Desktop Application with the JRuby and Java Swing APIs. Here we interview Teera to find out more about his interest in NetBeans Ruby.

First, tell us a little bit about yourself.

I've been working as a freelance software developer for about 8 years ever since finishing high school. My work mainly focuses on the web platform with various technologies ranging from Java, ASP.NET, PHP, and recently I got started on Ruby and Rails. Since November 2006, I've been hired by Sun as a campus ambassador at Simon University in British Columbia, Vancouver, where I'm completing my degree in Computing Science and Business Administration.

What is your interest in Ruby?

Coming from the strongly-typed language world of Java and C#, I find the flexibility and dynamic of the Ruby language to be very interesting. I believe that the productivity of developers has a heavy impact on the cost of software projects. I often find that I waste time waiting for the project to compile and re-deploy to web or application servers. So that's the first thing I found really appealing when I started working with the Ruby and Rails framework. Ruby seems to gain a lot of momentum on the web platform with the Rails framework. Now I'm more interested in the future of Ruby as a rich client on the desktop.

How did you learn Ruby?

I started out on Hal Fulton's The Ruby Way book to learn the Ruby language itself and the Ruby way of doing things. I often watch screencasts and vodcasts for techniques on learning Rails. I'm also a member of the Vancouver Ruby and Rails user group, where I attend monthly meetings. This is an interesting group; as a Java guy, I learn so much from others who work with Ruby on a daily basis.

What do you like and dislike about Ruby?

The Ruby language itself is beautiful. There are not many programming languages that are as intuitive and give me that "wow this is cool stuff!" sort of thrill. Of course, this is also because of Ruby's coding conventions and key principles.

I actually did a small experiment re-creating one of my old, small Java-based web projects with Ruby on Rails. I found that the entire project on RoR actually contains fewer lines of code than that in the previous version's configuration files!

In my opinion, performance and deployment are still the key issues of Ruby. JRuby and other initiatives are really aiming on these two issues.

How has NetBeans helped you build Ruby apps?

I tried RadRails, TextMate, and InstantRails. Yet, I like Netbeans Ruby support the most, especially in code editing, the Ruby debugger, and the auto-complete capability. Netbeans is tightly integrated with JRuby as well.

Tell us about the NetBeans Ruby app you are currently building?

I'm developing JSF web components for one of the my clients. There's future planning to release these components in rich client version (Swing and SWT). I'm doing an experimental project on how to leverage JRuby for developing these desktop components.

What was your favorite experience as a Sun ambassador?

Meeting with people! I made a lot of friends from around the world through this program. I also learned a lot from talking to people when I do evangelizing work, whether it's a tech demo or a presentation at a user group. Nothing beats learning from those who do real work out there in the field.

What are some things you like to do outside school and work?

I started a small coffee shop back when I was 19 and opened up a day-spa with my sister about two years ago. Both of them are in Thailand. So, I'm helping my sister run them remotely.

Where do you see yourself in five years?

Completing my degree is my first priority (it has been delayed several times due to my work). After finishing my term at Sun at the end of this year, I'll be joining Business Objects as a software developer. In the next five years, I might do another startup if there some good ideas come along, but things change, you never know.

Tuesday Oct 30, 2007

Ruby Getting Started Draft Available for Review

 

We have posted a draft of the first 2 sections of the Getting Started With Ruby and Rails tutorial. If you can take some time to look it over and give us feedback, please do.

For those of you who are new to using the NetBeans Ruby support, we would like to know:

  • How is it so far for getting you started with using the product?
  • Were the steps clear and complete? Did you stumble or have to try a step more than once to get it to work?
  • Is it too much for introductory material? If so, what to remove. If not enough, what to include.
  • Looking at the proposed table of contents, does it appear it will be complete? Too much?

For those of you who are experienced with Ruby, can you look for incorrect terminology or misinformation? Are the code examples ok?

To provide feedback on this tutorial, please send corrections, suggestions, and comments to the NetBeans Ruby Developers mailing list at dev@ruby.netbeans.org. Put "Getting Started Draft Feedback" in the subject line.

Monday Oct 29, 2007

Community-Contributed NetBeans Ruby Docs

In this blog, we would like to acknowledge two NetBeans Ruby community-contributed tutorials:

Thanks to Teera and Amit, we have a richer documentation set, which you can view in its entirety on the NetBeans Ruby Tutorials and Screencasts page.

If you are interested in contributing documentation to the NetBeans Community, consider joining the dev@userguide.netbeans.org email alias. This alias is for community members who want to not only contribute documentation but also provide input and feedback regarding existing NetBeans documentation. You can sign up for the alias as follows:

  1. Go to the NetBeans Mailing Lists Page
  2. Log on with your user name. If you don't have a user name, click Login and then register for a login name.
  3. Scroll to the dev@usersguide.netbeans.org mailing list.
  4. Click subscribe to send a subscription request.

Friday Oct 19, 2007

Got Ruby Questions?

Next week (October 22 - 26) you will have the opportunity to submit written questions about all things NetBeans to a team of NetBeans evangelists, including Ruby technology evangelist Brian Leonard.. You can submit a question any time during that week, and the evangelists will try to answer as many questions as possible. They will also post a selected set of questions and answers. To learn more, visit the Ask the Experts events page.

Monday Oct 15, 2007

Chart for NetBeans Ruby Database Access Setup

I have written both an installation and configuration article and an accessing databases FAQ for projects built using NetBeans Ruby support. However, because there are lots of different configuration paths, and each path requires some in-depth information, neither of these documents make it easy to quickly figure out what you must do to set up your Rails project to access your database server. I created this chart to hopefully make the steps simpler, and more clear. If you need more details, then consult the two documents that I mention above.

Steps for Accessing Databases Using NetBeans Ruby Support
 
Using JRuby
 
Using MySQL
 
   Using JDBC
Do:  Put the MySQL JDBC 3.0 compliant driver in netbeans-install-dir/ruby1/jruby-1.0.1/lib.
Do:  Select the database server from the drop-down list in the New Project wizard.
Do:  Select the Access Database Using JDBC checkbox in the New Project wizard.
 
  Using the Bundled MySQL Adapter
Do:  Select the database server from the drop-down list in the New Project wizard.
Do:  Clear the Access Database Using JDBC checkbox in the New Project wizard.
 
Not Using MySQL
   Do:  Put database's JDBC 3.0 compliant driver in netbeans-install-dir/ruby1/jruby-1.0.1/lib
Do: Select the database server from the drop-down list in the New Project wizard.
Do: Select the Access Database Using JDBC checkbox in the New Project wizard.
Notes: Currently, the supported databases are: MySQL, PostgresSQL, Oracle, HSQLDB, and Java DB (also known as Derby). The database's JDBC driver must be a pure Java driver. If you are deploying to GlassFish, you must also put a copy of your database server's JDBC driver in glassfish-install-dir/lib and start (or restart) the GlassFish server.

 
Using Native Ruby
 
Using MySQL
  
Using the Bundled MySQL Adapter
   Do:  Select the database server from the drop-down list in the New Project wizard.
Do:  Clear the Access Database Using JDBC checkbox in the New Project wizard.
  
Using a MySQL Gem
   Do:  Consult Ruby on Rails MySQL page. Download and install appropriate software.
Do:  Select the database server from the drop-down list in the New Project wizard.
Do:  Clear the Access Database Using JDBC checkbox in the New Project wizard.
  
Not Using MySQL
   Do:  Consult the Ruby on Rails Database Drivers page. Download and install appropriate software.
Do:  Select the database server from the drop-down list in the New Project wizard.
Do:  Clear the Access Database Using JDBC checkbox in the New Project wizard.
All
   Do:  Edit database.yml to specify username, password, and, if necessary, database name.

Wednesday Sep 26, 2007

Using jMaki 1.0 With NetBeans Ruby

The jMaki 1.0 framework, with support for Java, PHP, and Ruby, was released yesterday. Last week, Arun Gupta posted a screencast showing how to use jMaki wrappers of button and table widgets from Dojo and Yahoo frameworks in a Ruby on Rails application built using the NetBeans 6.0 Beta IDE.

With Arun's permission, I am supplying the steps to recreate a similar jMaki on Rails project. To save steps, I changed the order a bit. If you don't already have NetBeans Ruby Support, go to the Installing and Configuring Ruby Support tutorial for instructions.

  1. Before you begin, create the database for this Rails application. You need a database server that is supported by JRuby, such as MySQL, Java DB, PostgresSQL, Oracle, or HSQLDB. Add a database instance named rorjmakitables_development. For example, for MySQL, start the server and type the following at a command prompt.
    mysqladmin -u root -p create rorjmakitables_development
    If you don't need a password, omit the -p.

  2. If you haven't already, download the jMaki NetBeans plugin (This is org-netbeans-modules-sun-jmaki.nbm. The installer tells me it is version 1.6.11, and the info.xml in the NBM says its release date is Sept. 25, 2007).

  3. To install it into the IDE, complete the following steps:

    1. In the IDE, choose Tools > Plugins from the main menu.

    2. Click the Downloaded tab and click Add Plugins.

    3. Navigate to and select the downloaded org-netbeans-modules-sun-jmaki.nbm module, then click Open.

    4. Click Install, and click Next.

    5. Select the radio button to accept the license agreement and click Install.

    6. Select Restart IDE Now and click Finish.

  4. To create a new Ruby on Rails project, complete these steps:

    1. Right-click on a blank spot in the Projects window, and choose New Project from the pop-up menu.

    2. Select Ruby in the Categories pane, select Ruby on Rails Application in the Projects pane and click Next.

    3. If you have other Ruby installations in your path besides the bundled JRuby installation, you are asked to choose a Ruby interpreter. This dialog only pops up the first time the IDE needs to access the interpreter. For this tutorial, choose JRuby and then click Close. Note that this choice affects all Ruby projects. You can switch this setting whenever you want. See Installing and Configuring Ruby Support to learn how.

      If you have configured the IDE to not use JRuby, please use the Options wizard to switch back to JRuby for this tutorial, as described in Installing and Configuring Ruby Support.

    4. Type rorjmakitables, and accept the default location or, optionally, enter a different path.

    5. Choose a Database from the drop-down list. Your choice specifies how to set up the database.yml file. This tutorial uses MySQL.

      At the time of this writing, Java DB is not on the list, but it probably will be added later. So, if you are using the Java DB, and you don't see it on the list, don't bother selecting a database. You can edit the database.yml file instead. See Using Database Servers With JRuby for instructions.

    6. With JRuby, if you don't use MySQL, you must select the Access Database Using JDBC checkbox. This causes the project to modify the environment.rb configuration file to use the ActiveRecord-JDBC gem. So, unless you are using MySQL, check this box.

    7. Click Next.

    8. Because you are using the bundled JRuby, which includes Rails, the wizard shows that Rails is already installed. The wizard gives you the option of updating the installed version, but let's skip that.

      Click Finish.

      The Generate Rails Project tab in the Output window shows all the folders and files that the IDE creates.

  5. The IDE opens the database.yml file in the editor. Set the username for the development configuration, as shown below. If your database requires a password, set the password too.
      development:
      adapter: mysql
      database: rorjmakitables_development
      username: root
      password: root_password
      host: localhost
    
  6. To add a controller, right-click the rorjmakitables project node in the Projects window, and choose Generate. Select controller from the Generate drop-down list, set the Name to say and set the View to table, then click OK.

  7. In the Projects window, expand Configuration and double-click routes.rb to open it in the editor.

  8. Add the following line above all the other map.connect entries.
      map.connect '', :controller => 'say', :action=>'table'
    
  9. In the Projects window, expand Public, right-click index.html and choose Delete (or Rename if you would rather rename the file).

  10. In the Projects window, expand Views, expand say, and double-click table.rhtml to open it in the editor.

  11. On the right-side of the IDE is the Palette, as shown below. Expand jMaki Yahoo.



  12. Drag a Button widget from the jMaki Yahoo section and drop it on the file.

  13. Drag and drop a second Button widget.

  14. Replace the widget code fragments with the following code.
    <%= jmaki_widget 'yahoo.button',
      :value => { :label => 'Select 1',
      :action => { :topic => '/jmaki/table/select',
        :message => { :targetId => '1' }
      }
    } -%>
    <%= jmaki_widget 'yahoo.button',
      :value => { :label => 'Select 2',
      :action => { :topic => '/jmaki/table/select',
        :message => { :targetId => '2' }
      }
    } -%>
    
    These buttons use the jMaki publish/subscribe mechanism to publish to the /jmaki/table/select topic, which you will program two table widgets to listen to. The table widgets will select either the first row or the second row, depending on which button is clicked. For more details on how to use publish/subscribe, see Carla Mott's Widgets Talking To Widgets blog entry.

  15. Drag a Data Table widget from the jMaki Yahoo section onto the file.

  16. Expand jMaki Dojo and drag a Table widget from that section onto the file.

    Both these widgets use the jMaki Table Data Model.

  17. Add :subscribe=> "/jmaki/table", to each table widget, as shown in bold below, to make both tables listen to all the /jmaki/table topics.

    (Important)Also, change the row data to include numeric ids, as shown in bold, so that they match the target ids in the button code. For the first row, you have to add :id= > '1',. For the second row, which already has the :id argument, simply change bar to 2.
    <%= jmaki_widget 'yahoo.dataTable', :subscribe=> "/jmaki/table",
      :value =>
      {:columns => [
        { :label => 'Title', :id => 'title'},
        { :label => 'Author', :id => 'author'},
        { :label => 'ISBN', :id => 'isbn'},
        { :label => 'Description', :id => 'description'}
      ],
      :rows => [
        { :id=> '1', :title => 'Book Title 1', 
              :author => 'Author 1', :isbn => '4412', 
              :description => 'A Some long description'},
        { :id => '2', :title => 'Book Title 2', 
              :author => 'Author 2', :isbn => '4412', 
              :description => 'A Some long description'}
      ]
    }
    -%>
    <%= jmaki_widget 'dojo.table', :subscribe=> "/jmaki/table",
      :value =>
      {:columns => [
        { :label => 'Title', :id => 'title'},
        { :label => 'Author', :id => 'author'},
        { :label => 'ISBN', :id => 'isbn'},
        { :label => 'Description', :id => 'description'}
      ],
      :rows => [
        { :id=> '1', :title => 'Book Title 1', 
              :author => 'Author 1', :isbn => '4412', 
              :description => 'A Some long description'},
        { :id=> '2', :title => 'Book Title 2', 
              :author => 'Author 2', :isbn => '4412', 
              :description => 'A Some long description'}
      ]
    }
    -%>
    
  18. Click the Run Main Project button on the main menu (the green arrow). This starts the server and opens the table view in a browser.

  19. Click the first button to select the first row, and click the second button to select the second row.

  20. In order to display database data in the table, we must first create a model. In the Projects window, right-click the project node, and choose Generate from the pop-up menu.

  21. Choose model from the Generate drop-down list, type grid in the Arugments text box, and click OK.

  22. To define the model's data structure, expand Data Migrations in the Projects window, then expand migrate and double-click 001_create_grids.rb to open it in the editor.

  23. Replace the up method with the code shown in bold.
    class CreateGrids < ActiveRecord::Migration
    
     def self.up
        create_table :grids do |t|
          t.column :title, :string
          t.column :author, :string
          t.column :isbn, :string
          t.column :description, :string
        end
        Grid.create(:title=> 'Marathon',
           :author=> 'Jeff Galloway',
           :isbn=> '0936070250',
           :description => 'A running book for everybody');   
        Grid.create(:title=> 'The Runners Bible',
           :author=> 'Marc Bloom',
           :isbn=> '0385188749',
           :description => 'How to train, race, and get in shape');   
      end
    
      def self.down
        drop_table :grids
      end
    end
    
  24. To create the database table and populate it with the two rows of data, right-click the project node in the Projects window and choose Migrate Database > To Current Version from the pop-up menu.

  25. Now you can define a variable that contains the data from the database table. In the Projects window, expand Controllers and double-click say_controller.rb to open it in the editor.

  26. Replace the table definition with the following code shown in bold.
    class SayController  < ApplicationController
    
      def index
        table
        render :action => 'table'
      end
     def table
        @rows_data = []
        Grid.find_all().each do |data|
          @rows_data  << { :id => data.id,
            :title => data.title,
            :author => data.author,
            :isbn => data.isbn,
            :description => data.description
          }
        end
      end
    end
    
    The above code defines the rows_data variable and initializes it to an empty array. It uses the active record to find all the rows from the database and, for each row, add a hash of the fields to the rows_data array.

  27. Return to the table.rhtml view by right-clicking in the editor and choosing Navigate > Go To Rails Action or View.

  28. Replace the static rows data in the table fragments with the @rows_data variable as shown in bold below.
    <%= jmaki_widget 'dojo.table',
    :value =>
    {:columns => [
         { :label => 'Title', :id => 'title'},
         { :label =>'Author', :id => 'author'},
         { :label => 'ISBN', :id => 'isbn'},
         { :label => 'Description', :id => 'description'}
         ],
      :rows => @rows_data
      }
    -%>
    <%= jmaki_widget 'yahoo.dataTable',
    :value =>
    {:columns => [
         { :label => 'Title', :id => 'title'},
         { :label => 'Author', :id => 'author'},
         { :label => 'ISBN', :id => 'isbn'},
         { :label => 'Description', :id => 'description'}
         ],
      :rows => @rows_data
      }
    -%>
    
  29. Choose File > Save All from the main menu to save all your changes.

  30. Go back to the browser and refresh the page. The data now comes from the database table.

There you have it! To learn more about jMaki, go to www.jmaki.com. To learn more about NetBeans support for Ruby, go to wiki.netbeans.org/wiki/view/Ruby.

About

divas

Search

Archives
« April 2014
SunMonTueWedThuFriSat
  
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
   
       
Today