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 19, 2009

Rails Generate Window Not Appearing With JDK 6u12

A few people have reported that when they right-click a Rails project node in the NetBeans IDE and choose Generate from the pop-up menu, nothing happens. One user reported that the problem is caused by an interaction with the Java Development Kit (JDK) 6u12. To fix this problem, download a different version of the JDK, such as 6u11, and point the IDE to that installation. See my previous blog for instructions on how to use a different JDK.

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 Feb 03, 2009

no such file to load -- mysql

Rails never fails me. As soon as I publish a series of tutorials for a NetBeans release, a new Rails release comes out which breaks my tutorials (and, apparently, most everyone else's). Gratefully, some customers took the time to click the Feedback button at the end of our tutorials to let us know the tutorials were no longer working. One customer wrote:

"When trying to create the database following the steps indicated, I got an error indicating the mysql gem had been removed from Rails 2.2.2 and that I should install the mysql gem. (Note from me: the actual error message is "The bundled mysql.rb driver has been removed from Rails 2.2. Please install the mysql gem and try again: gem install mysql.") However, that gem is also native and can't be installed with JRuby (the misleading directive to do so from NetBeans was really annoying)."

I have to agree that this is indeed REALLY annoying. However, the "misleading directive" comes from Rails, and not from NetBeans. And, since Rails 2.2 came out after NetBeans 6.5, this was an unexpected message.

While the directive may be true for Ruby, it is not true for JRuby, because the the MySQL adapter is included with JRuby. In addition, as the user pointed out, you can't install the mysql gem with JRuby because you cannot use any gems that build native C libraries during the install process, and that includes the mysql gem.

I did some googling and found two solutions:

  • Use the activerecord-jdbcmysql-adapter. You can find the instructions on how to do that here.
  • Copy the MySQL driver to your project's lib folder. If you have an older Rails version, you can copy the Ruby MySQL driver (mysql.rb) from rails-install-dir/gems/activerecord-version/lib/active_record/vendor/mysql.rb to the project's lib directory. Unfortunately, you have to do this for every JRuby project.

If anyone else has any other solutions, please post a comment.

P.S. For all you Ruby programmers, when you try out a tutorial, you really should pay attention to what gem versions the tutorial was written for. Gem releases such as Rails and RSpec are not always backwards compatible, so there is a chance that the tutorial will not work with releases that came out after the tutorial was written.

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

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.

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.

Monday Jul 07, 2008

How Do I Access Databases From My JRuby Rails Project?

Over the last year, as I wrote and updated the Ruby tutorials, I end up with many different versions of the Rails applications, where each is based on a different version of JRuby. I often test with both Ruby and JRuby, and I try to test them using different database servers. Rather than follow a tutorial from scratch to get a working version for my current configuration, I wanted to learn how to easily take an application and change it to work with a different database configuration. For example, how can I take an application that I developed using the native Ruby interpreter, and make it work using the JRuby interpreter, or take an MySQL application and use it with a PostgreSQL server. As I researched the history of JRuby access to databases, I compiled my notes into a FAQ, which I posted to wiki.netbeans.org/FaqRailsJRubyDatabaseAccess.

Hopefully, you will find it helpful. If not, post a comment as to what other information you would like to see, or let me know when the instructions don't work. Even better, you can correct the FAQ itself if you have joined the NetBeans community.

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.

Tuesday Jan 15, 2008

Creating a Rails 2.0 Ruby Weblog in 10 Minutes

THIS TUTORIAL IS FOR NETBEANS IDE 6.0. IF YOU ARE USING NETBEANS 6.1, SEE THE UPDATED TUTORIAL ON THE NETBEANS RUBY TRAILS PAGE.

Note: On 2/25/08, I updated Code Sample 3 to take advantage the REST URLs and Path methods that the map.resources entity in the routes.rb generates. I also modified Step 3 in the last Doing More section to match the modified code.

Our Ruby weblog tutorial series for NetBeans IDE 6.0 is written for Rails 1.2.5 and uses the ActionController scaffold method. The Rails 2.0 framework dropped this method, so the tutorials do not work if you have updated to Rails 2.0.

We are now learning about the 2.0 changes so that we can produce updated tutorials. In the meantime, here is a quick draft of how to do the first weblog tutorial, Creating a Ruby Weblog in 10 Minutes, using the Rails 2.0 framework and the NetBeans 6.0 IDE. We are still learning about the new Rails 2.0 features, so there will probably be many changes to come. Please consider this a temporary document.

Currently, this tutorial assumes that you are using a native Ruby interpreter, and have updated to Rails 2.0 (I believe you need to update RubyGems as well). There are many flavors of Ruby, one of which can be download from ww2.ruby-lang.org. To learn how to set up the IDE to use a native Ruby interpreter, see Installing and Configuring Ruby Support.

Note: This tutorial uses the MySQL database server. See Installing and Configuring Ruby Support for information about using a MySQL database server in a Ruby application that is built using the NetBeans 6.0 IDE.

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 in the Categories field and Ruby on Rails Application in the Projects field. Click Next.

    Note: The first time that you create a Ruby project in the IDE, the IDE checks if you have any other Ruby installations in addition to the bundled JRuby software. If you do, the IDE displays a dialog box asking you to select which software to use. Choose the native Ruby interpreter.

  3. Type rubyweblog in the Project Name field. Accept all the other default settings.
  4. Click Finish to create the new project.

    The IDE creates the project directory with the same name as your project.

Configuring the Database Environment

The next step is to edit the file database.yml, which is already configured to use the MySQL adapter and the development database. You do not need to do any configuration unless the root user requires a password.
  1. In the editing area, edit the database.yml by providing the password in the development configuration.
  2. Save and close the database.yml file.

    Note: If your operating system's host file does not contain localhost, use 127.0.0.1 instead.

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

Creating the Scaffold

Here you use the Rails Generator to create a scaffold and a model for the application. The rubyweblog application requires a Post model for storing instances of blog posts.

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

  2. In the Rails Generator dialog box, choose scaffold from the Generate drop-down list.

  3. Type Post title:string in the Model Name field and click OK (Controller Name and Actions not valid arguments in Rails 2.0).

    The Rails Generator creates a model named Post, creates a migration file, and adds the controller and views for listing, creating, updating, and deleting posts. In addition, Rake edits the routes.rb file to map Post as a resource. The Output window lists the files that are created as part of the model generation.

Migrating the Database

The file that you work with next is the migration file, 001_create_posts.rb.
  1. In the Output window, click the link for the db/migrate/001_create_posts.rb file.

    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

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

    Note that Rails 2.0 provides some new db Rake tasks, such as create (which you used earlier), drop, reset, rollback, and version.

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. Expand the Public node, right-click index.html and choose Delete.

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

Doing More: Adding Another Field

Here you add another field so that, in addition to the Title field, the posts table includes a Body column for providing the text of the blog.

  1. Right-click the Database Migrations node and choose Generate. In the Rails Generator dialog box, type AddBodyToPost body:text in the Arguments field 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:

    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. Choose File > Save All.
  3. 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.
  4. Typically, you would now edit the views to add the new field. For this tutorial, you will simply regenerate the scaffold. In the Projects window, right-click the rubyweblog project node and choose Generate.

  5. In the Rails Generator dialog box, choose scaffold from the Generate drop-down list.

  6. Type Post title:string body:text --skip-migration in the Model Name field.

  7. Select the Overwrite radio button.

  8. Click OK.

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

  10. 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 3: Code for index.html.erb
    <h1>The Ruby Blog</h1>
    
    <% for post in @posts %>
      <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.

  2. Run the application to see the new interface for the Post model.

  3. To display the blog with the most recent entry first, reverse the sort order by adding .reverse to the end of @posts in index.html.erb:

    	  <% for post in @posts.reverse %>
    	  

    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.

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

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

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

Tuesday Oct 09, 2007

Generating Rails Models

Our NetBeans Ruby tutorials show how to use the Rails Generator dialog box to add models to a Ruby on Rails web application. We show one step that uses the Rails Generator wizard to create the following:

  • Model File: This file contains the model's unique methods and business rules.
  • Initial Migration Files: Migration file for creating the database table. You run the migration files to create and modify the database table, and to back out changes
  • Unit Text Files: Files for testing your development.

In the subsequent step we have you edit the migration file to specify the column names and types. Did you know that you can can create the model and edit the migration file in one step by passing arguments in the Rails Generator? For example, let's say that I wanted a categories database table. I can right-click the project's node and choose Generate. In the Rails Generator wizard, I choose model from the Generate drop-down list. Then, I enter the following text in the Argument text box, and click OK to create the files:

Category name:string description:text level:integer created:timestamp icon:binary

The arguments list begins with the model name and is followed by column-name:type parameters. The type can be one of :string, :text, :integer, :float, :decimal, :datetime, :timestamp, :time, :date, :binary, :boolean. To learn more about model arguments, see the TableDefinition API.

After the IDE finishes creating the files, I can click on the create db/migrate/002_create_categories.rb link in the Rails Generator tab in the Output window to open the file in the editor. The contents looks like this:

class CreateCategories < ActiveRecord::Migration
  def self.up
    create_table :categories do |t|
      t.column :name, :string
      t.column :description, :text
      t.column :level, :integer
      t.column :created, :timestamp
      t.column :icon, :binary
    end
  end

  def self.down
    drop_table :categories
  end
end

Once you have a migration file set up, you can move your application to another machine and have the IDE create the tables automatically. The same is true for database changes. With the up and down methods, you can quickly add or back out changes. Migrations also make it easier to switch to a different database server, say from JavaDB to MySQL.

Note: If you have an existing database, and you want to quickly create migration files, right-click the project node and choose Run Rake Task > db > schema > dump. The IDE writes the schema for your database to Database Migration > schema.rb. You can copy the create statements from the schema dump into migration files.

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