Tuesday Nov 03, 2009

A New Day a New Blog

It has been almost two years since the divas were split up -- Gail works on JavaFX and I work on Cloud Services. I have been thinking about starting a new blog ever since, and I finally got around to doing it. From now on, I will be posting at altocirrus.wordpress.com. In addition to talking about NetBeans, Ruby, and Rails, I will be getting into cloud applications and other bits of cloud information that I come across.

- diva#2

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.

Wednesday Feb 18, 2009

Using Gems With JRuby

If you are new to JRuby, you might not know that you cannot use a gem that has native extensions with JRuby, unless that gem builds its library in a platform-neutral manner. When you use the JRuby gem executable to try to add such a gem to your repository, you will get a message like this.

Building native extensions.  This could take a while...
ERROR:  Error installing rmagick:
    ERROR: Failed to build gem native extension.

C:/jruby/jruby-1.1.5/bin/jruby.bat extconf.rb install rmagick --no-rdoc --no-ri
C:/jruby/jruby-1.1.5/lib/ruby/1.8/mkmf.rb:7: JRuby does not support native extensions. Check wiki.jruby.org for alternatives. (NotImplementedError)
    from C:/jruby/jruby-1.1.5/lib/ruby/1.8/mkmf.rb:1:in `require'
    from extconf.rb:1
Gem files will remain installed in C:/rubyrepos/jrubygemrepo/gems/rmagick-2.9.1 for inspection.
Results logged to C:/rubyrepos/jrubygemrepo/gems/rmagick-2.9.1/ext/RMagick/gem_make.out

As you would guess, you then need to hunt for an equivalent gem that will work with JRuby. Anything with "pure Ruby" in its description is a good bet. In the case of RMagick, there is a RMagick4j. Some other examples JRuby compatible gems are Mongrel, Hpricot, ImageVoodoo, JRuby-OpenSSL, JRuby/LDap, json_pure, and postgres_pr.

If you are developing with both Ruby and JRuby, you might want to create a separate repository that holds the gems that work for both implementations, and then put that repository into your GEM_PATH. That way, you won't have to install the gem twice. If you are using NetBeans IDE, use the Ruby Platform Manager to add the repository to a platform's GEM_PATH.

If you want to require a certain gem based on whether you are running on JRuby, you can check whether JRUBY_VERSION is defined.

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

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

Tuesday Nov 18, 2008

My Favorite NetBeans Features

There has been one NetBeans feature that has been a life saver for me. It was around in 6.1, but I didn't know about it until I saw Brian Leonard use it in our JavaOne hands-on lab to figure out what a lab participant had done wrong -- local history. He used it to back track what the guy had done to see where he deviated from the lab.

As a tech writer, I spend a lot of time trying to figure out how to do something without the advantage of having documentation (cart before the horse thingee). If my experiments don't work, I right-click the file's tab in the editor and choose Local History > Show Local History. I can use the local history to quickly and safely back out my changes and try a different route. I can also use it to highlight the code that I changed (see below) so that I can examine it carefully to make sure I didn't make a mistake.

Comparing files is old technology that has been around since UNIX was invented (probably even before that), but NetBeans takes it to the next level. For example, I recently realized that I had accidentally made changes to a duplicate file instead of the one I was currently working on. Rather than trying to remember what I had done, and then trying to recreate the changes exactly, I simply opened the working document in the editor, right-clicked on the tab, and chose Diff To. I pointed to the older version and got the following output. All I had to do was click the arrows to bring the changes over to the new file.

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.

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.

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.

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.

Thursday Jan 03, 2008

Adding a Popup Window to a NetBeans 6.0 Visual Web Page

Here is a mini-tutorial for creating a Popup window for the user to lookup values. One scenario that you might use this for is when the page visitor needs more information then can be displayed in a drop-down list.

This is a rewrite of a previous blog entry that was written for the Sun Java Studio Creator IDE. I have modified the steps so that it works for the NetBeans 6.0 IDE.

  1. Create a web application project with the Visual Web JavaServer Faces framework.

  2. Add a page named Popup.

  3. Add a Table component to the page.

  4. Drag VIR > Tables > State from the Services window and drop it on the table.

  5. Right-click the Table component and choose Table Layout from the pop-up menu.

  6. In the column for the STATE.STATEID database field, set the Component Type to Hyperlink, and click OK.

  7. Select the Hyperlink component so that its properties appear in the Properties window.

  8. Set the value for the onClick property to doSave('#{currentRow.value['STATE.STATEID']}')

    (I got the value to pass to doSave() from the Value Expression in the Table Layout dialog).

  9. Drag a Script component from the Advanced section of the Palette and drop it on the page.

  10. Click JSP in the editing toolbar to view the JavaServer Pages script.

  11. In the JSP page, change the <webuijsf:script> tag as shown below.

     
    <webuijsf:script binding="#{Popup.script1}" id="script1">
    <![CDATA[
    function doSave(val) {
     window.opener.setVal(val);
     window.close();
    }]]>
    </webuijsf:script>
    


    The Popup page is now ready for use by another page.

  12. Create a new page called Form1. Make it be the start page.

  13. Drag a Text Field component and drop it on the page. In the Properties window, make sure the id is set to textField1.

  14. Drop a Hyperlink component on the page, just above the text field, and set the text property to State Code.

  15. Set the url property to /faces/Popup.jsp.

  16. Set the onClick property to doPopup('form1:textField1_field')

    Note: Here you are passing the id of the field to fill with the selected value. Determining the id can be tricky. To determine what to use for the id, run the application, and use a tool such as Firebug to inspect the DOM.

  17. Click the ... button for the target property to open the target property editor.

  18. In the property editor, click New and set both the Display and Value to popup. Click OK and click OK again.

    Later you add script to open a window named popup, and this setting causes the Popup.jsp page to display in that window.

  19. If the target property value is still blank, select popup from the value from the combobox for that property.

  20. Drag a Script component from the Advanced section of the Palette and drop it on the page.

  21. Click JSP in the editing toolbar to view the JavaServer Pages script.

  22. In the JSP page, change the <webuijsf:script> tag as shown below.

     
    <webuijsf:script binding="#{Form1.script1}" id="script1">
    <![CDATA[
    function doPopup(destination) {
     popup = window.open("", "popup",
     "height=300,width=200,toolbar=no, menubar=no,scrollbars=yes");
     destinationElement=document.getElementById(destination);
     popup.focus();
    }
    
    function setVal(val){
     destinationElement.value=val;
    }]]></webuijsf:script>
    


  23. Run the project. Click State Code to open the popup window. Click a state code to select the code, close the popup window, and populate the text field.

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.

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