The Source for Java Technology Collaboration
User: Password:



Brian Leonard's Blog

March 2007 Archives


Building a Ruby Sample for NetBeans

Posted by bleonard on March 26, 2007 at 03:26 PM | Permalink | Comments (9)

We're in the process of creating some sample applications to ship with the NetBeans Ruby module, one of which will be based on the screencast, Putting Flickr on Rails. You can just download and run the sample project (you'll have to set your Flickr API Key), or build it from scratch as documented here.

Setting Things Up

  1. Download and install NetBeans 6.0 M7 or greater.
  2. Install the Ruby module from the update center (found in the Features folder. Many dependant modules will come along). The Ruby module requires a restart of the IDE.
  3. Apply for a Flickr API Key which you'll need to access the Flickr APIs.
  4. Get the Flickr library. Unless you've added gem to your path, browse to its location in your user directory and run gem install -r flickr.


Create the Search Dialog

In this step will create the Ruby on Rails application and a page for searching the Flickr database by tag.

  1. Create a new Ruby on Rails application named Flickr.
  2. The Flickr library expects you to add your Flickr API Key directly to its script. You could do that, however the approach here allows us to use the Flickr library without touching it. Open environment.rb and add the following to the bottom. Remember to enter your Flicker API Key.

    require 'rubygems'
    require 'flickr'
    MY_KEY='Enter your Flicker API Key'
    class Flickr
      alias old_initialize initialize
      def initialize(api_key=MY_KEY, email=nil, password=nil)
        puts "new_initialize " + MY_KEY
        old_initialize(api_key, email, password)
        @host="http://api.flickr.com"
        @activity_file='flickr_activity_cache.xml'
      end
    end
  3. Right-click the Views -> layouts folder and select New -> Empty RHTML (Embedded Ruby) file. Name the file application.
  4. Add the following HTML:

    <html>
        <head>
            <title>Flickr</title>
            <%= javascript_include_tag :defaults %>
            <%= stylesheet_link_tag 'flickr' %>
        </head>
        <body>
            <%= yield %>
        </body>
    </html>
  5. Right-click the Public -> stylesheets folder and select New -> File/Folder. Then select XML -> Cascading Style Sheet. Name if flickr. Add the following styles:

    body {
        background-color: #888;
        font-family: Lucida Grande;
        font-size: 11px;
        margin: 25px;
    }

    form { margin: 0; margin-bottom: 10px; background-color: rgb(222,231,236); border: 5px solid #333; padding: 25px; }
    fieldset { border: none; } #spinner {
    float: right;
    margin: 10px;
    }

    #photos img { border: 1px solid #000; width: 75px; height: 75px; margin: 5px; }
  6. Right-click the Controllers node and select Generate. Set the name to flickr and the Views to index. Put the following in index.rhtml:

    <%= form_remote_tag :url => {:action => 'search'}, :update => 'photos' %>
        <fieldset>
            <label for="tags">Tags:</label>
            <%= text_field_tag 'tags' %>
            <%= submit_tag 'Find' %>
        </fieldset>
    <div id="photos"></div>
    <%= end_form_tag %

Pause to Test

Here we will configure the environment so that running the project launches our application:

  1. Stop the WEBrick server by clicking the red in the Output window:


  2. Delete index.html from Public.
  3. Open routes.rb and add the following to the bottom of the file:

    map.connect "", :controller => 'flickr'
  4. Press F6 to start WEBRick and launch the application.


Define the Search Method

  1.  Switch to the FlickrController class and add the following:

    class FlickrController < ApplicationController
      def search
        flickr = Flickr.new
        render :partial => 'photo', :collection =>
          flickr.photos(:tags => params[:tags], :per_page => '24')
      end
    end
  2. Right-click the Views -> flickr folder and select New -> Empty RHTML (Embedded Ruby) file. Name the file _photo and replace its contents with the following:

    <img class='photo' src="<%= photo.sizes[0]['source'] %>">
    
  3. Return to your browser and enter a search string (give the images a couple of seconds to load):

Improve The User Experience

When you click find, there's no feedback that something's happening behind the scenes. We'll add a simple animated gif to help address this as well as change the effect of the images loading.

  1. Drag this animated gif to your Public -> images folder.
  2. Modify index.rhtml as follows (the parts in bold were added)

    <%= form_remote_tag :url => {:action => 'search'}, :update => 'photos', 
        :complete => visual_effect(:blind_down, 'photos'),
        :before   => %(Element.show('spinner')),
        :success  => %(Element.hide('spinner')) %>
    <%= image_tag 'spinner.gif', :id => 'spinner', :style => 'display: none' %>
    <fieldset> <label for="tags">Tags:</label> <%= text_field_tag 'tags' %> <%= submit_tag 'Find' %> </fieldset>
    <div id="photos" style="display: none"></div>
    <%= end_form_tag %>
  3. Return to your browser and try another search string.



    Now you get a simple animation to let you know the server is working on your request and when the images do appear, they drop down like a set of blinds.


Using IRB in NetBeans

Posted by bleonard on March 23, 2007 at 11:17 AM | Permalink | Comments (5)

I've been playing around with the IRB (Interactive Ruby Shell) Console in NetBeans. Generally, IRB is started from the command prompt in the directory containing your scripts. However, in NetBeans, it's launched from the NetBeans installation directory. So here are some tips on using IRB in NetBeans.

  1. Create a Ruby Application named IRBTest.
  2. In main.rb, define the following Blog class which we'll use for testing:


  3. From the Window menu, select IRB - Interactive Ruby Shell:



  4. The console will open in the editor's Output pane:



  5. Check your version of Ruby:



  6. Try to create a new Blog:



  7. The main.rb script file needs to be loaded into IRB first.



  8. Enter Dir.pwd



  9. Change to your project's lib directory:



  10. Try loading main.rb again:



  11. And now we can work with it:



  12. Add a body attribute to the class as follows:



  13. The try to set the body attribute:



  14. The script just needs to be reloaded and then you can use the up arrow to rerun the blog.body command:



  15. Closing the IRB window does not terminate your session (which is a good thing). To terminate your IRB session, type quit or exit.


Instant Rails with NetBeans

Posted by bleonard on March 19, 2007 at 11:24 AM | Permalink | Comments (8)

Two weeks ago I introduced myself to Ruby on Rails, which was, technically, JRuby on Rails. Based on some constructive comments by David Rupp, I've spent some time over the past week doing some additional research on rails. In the process I began to look at pure Ruby (not JRuby).

Now, I'm sorry, this blog entry is somewhat Windows biased, which feels odd for a guy that normally talks about Java. However, playing with Ruby for the past week I realized the easiest way to get up and running with Rails on Windows is to use Instant Rails, which contains everything you need in one nice package: Ruby, Rails, Mongrel and MySQL.

Setting Things Up

Instant Rails

  1. Download and extract Instant Rails.
  2. Run InstantRails.exe. The first time InstantRails.exe runs, it will want to update the paths in the Rails configuration files to the location you extracted the archive. InstantRails starts Apache (which you can stop) and MySQL.



  3. Create an environment variable named RUBY_HOME that points to the Ruby location within Instant Rails. For example: C:\Software\Ruby\InstantRails-1.6-win\InstantRails\ruby.
  4. Add %RUBY_HOME%\bin to your Path environment variable.

NetBeans

  1. Download and install NetBeans 6.0 M7 or greater.
  2. Download and save the MySQL JDBC driver somewhere on your workstation. We need this to use the NetBeans Database tools with MySQL.
  3. Start NetBeans and switch to the Runtime tab (Ctrl+5).
  4. Expand the Databases > Drivers node and right-click to add a new driver.
  5. Browse to the location where you saved the MySQL JDBC driver. NetBeans will detect the driver class and recommend a name:



    Click OK.
  6. Right-click the MySQL (Connector/J driver) now listed under Drivers and select Connect Using. Instant Rails comes with a sample database called cookbook, that we can use to test our connection:



  7. If all goes well, you should be able see your connection and browse the database:




  8. Install the Ruby module from the update center (found in the Features folder. Many dependant modules will come along). The Ruby module requires a restart of the IDE.
  9. The Ruby module also installs JRuby and Rails. However, we're going to point NetBeans at the location where Instant Rails installed Ruby. Open the Options dialog Under Miscellaneous, expand the Ruby Installation node and point NetBeans to the version of these files found in instant Rails installation


    .

Test the Installation

Instant Rails comes with a sample cookbook application which we'll set up in NetBeans. This will also serve as an example of how to set up existing rails projects you already have in NetBeans.

  1. Create a new Ruby on Rails Project From Existing Sources.
  2. Browse to your Instant Rails installation directory where you'll find a rails_apps folder. Select the cookbook folder under rails_apps and click Finish.
  3. The project will open in NetBeans and the Mongrel server will be started (The Output window says WEBrick, but it's actually Mongrel that's running. Also, the server is started even though the Output window just says STARTING. This issue has been logged.).
  4. Try the following: http://127.0.0.1:3000 and you should see the Online Cookbook.


  5. If you run into problems, check that you can verify the Instant Rails setup from the command line.

Create Your Own Rails Project

  1. Create a new Ruby on Rails Application project and click Finish.
  2. Right-click the Controllers folder and select Generate. Name the controller MyTest. NetBeans will run the script to generate the controller.
  3. Open the MyTestController class and add the following:


  4. Press F6 to run the project and browse to http://127.0.0.1:3000/My_Test. You get a Routing Error.



    This is because the Mongrel (and WEBrick for that matter) web server is only capable of handling one application at a time. It needs to be restarted when we switch to another application.
  5. Since we're letting NetBeans start the server, the only way I know to kill it is to kill the ruby.exe process using the Windows Task Manager. Kill ruby.exe, press F6 to run the project, and browse to http://127.0.0.1:3000/My_Test.

Another Way To Run Mongrel

Since NetBeans doesn't yet provide the best integration with Mongrel, you may prefer to run it from the command line. Let's see how this works.

  1. First, kill the ruby.exe again started by NetBeans.
  2. Open the command prompt to the location of your Rails application above. It should be named RailsApplication1 if you accepted the default name.
  3. Type ruby script/server (if ruby isn't found, make sure you set up your path correctly as described under setup above).



    Now you see there's at least a cleaner way to stop the server.
  4. To run the cookbook application, CTRL-C to stop mongrel, switch to the cookbook directory and run ruby script/server again.


If You Thought Rails Development Was Fast Before...

Posted by bleonard on March 05, 2007 at 02:32 PM | Permalink | Comments (10)

A while back I watched the Creating a weblog in 15 minutes video that everyone was raving about and I remember thinking, yuck, too much command line. Then my buddy Roman produced a webcast (to be published later this week) showing how to do the same in NetBeans 6.0 Milestone 7. So here for you, I produce the blow-by-blow, with a slight twist in that I use the Derby database that comes with JDK 6 in place of MySQL.

Setting Things Up

To continue we need NetBeans 6.0 M7 or greater and JDK 6 (because I'm going to use its bundled Derby database).

  1. Download and install JDK 6.
  2. Set your environment's CLASSPATH to the location of your derbyclient.jar. This is necessary in order for the WEBrick server to find the Derby library. On Windows this will default to:
         C:\Program Files\Java\jdk1.6.0\db\lib\derbyclient.jar    
  3. Download and install NetBeans 6.0 M7 or greater.
  4. Before launching NetBeans, customize your launcher to set your user directory to a location that doesn't contain spaces (this is to work around an issue with Rails), for example:
         --userdir D:\UserDirs\Ruby
  5. Install the Ruby module from the update center (found in the Features folder. Many dependant modules will come along). The Ruby module requires a restart of th IDE.

Create the Ruby Project

  1. Create a new Ruby On Rails Application named BlogDemo. Wait while the project is generated and the WEBrick Web Server is started.


  2. Run the project.
  3. Add blog to the end of the URL string (http://localhost:3000/blog). You should get "Recognition failed for "/blog".



    Let's create a blog controller.

Generate a Controller

  1. Right-click the Controllers folder and select Generate. Name the controller Blog.


  2. Once the controller is generated, switch back to the browser and refresh the page. It should now return an "Unknown action - No action responded to index".



    Let's define a simple index.
  3. Add the following to the BlogController class:


  4. Save BlogController and refresh the browser page. You'll now see a message indicating the index.rhtml template is missing.

  5. For now, try just adding the following to the index definition:


  6. Save BlogController and reload the browser page to see Hello World in your browser.

Using a Scaffold

One of Rails' strengths is how easy it is to work with data. Check this out:
  1. Edit database.yml (found in the Configuration folder) and replace the development database configuration with the following:
      adapter: jdbc
      driver: org.apache.derby.jdbc.ClientDriver
      url: jdbc:derby://localhost:1527/sample
      username: app
      password: app
  2. Switch to the Runtime tab and right-click the jdbc:derby://localhost:1527/sample node under Databases and select Connect. The default password is app.
  3. Right-click the node again and select Execute Command.
  4. Paste the following and execute:
     CREATE TABLE posts (
        ID INTEGER GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
        title VARCHAR(255)
     );
  5. If you expand the Tables node you'll see the POSTS table in the list (right-click and select Refesh if you don't see it).


  6. Switch back to the Projects tab, right-click the Models folder and generate a new model named post.
  7. Replace the index definition in BlogController with


  8. Unfortunately, this step requires a restart of the WEBrick server, and unfortunately, this isn't yet possible in NetBeans. If you know of the command line to shut down WEBrick, please let me know. So we need to kill the process, which on Windows can be a crapshoot. You want to find the JAVA.EXE process that's running at about 60K.



  9. Return to NetBeans and press F6 to run the project again, which will start the WEBrick server.
  10. Add blog to the end of the URL string (http://localhost:3000/blog) and test...






The Beauty of Rails

  1. Let's add a new column to our table. Execute the following SQL statement as explained above:
     ALTER TABLE posts ADD COLUMN body VARCHAR(256);
  2. Return to the browser and click on the Edit link to see how Ruby has recognized our new body field (we'll adjust the size next).


Generate a Scaffold to Customize the Display

  1. Right-click the Views folder and generate a scaffold named Post referring to the Blog controller.


  2. Open _form.rhtml and change the text_field to a text_area for Body.


  3. Save the file and refresh the browser.


Make the List Look More Like a Blog:

Add a few more entries, for example:


Let's modify our scaffold so it looks more like your typical blog:

  1. Open list.rhtml and delete the entire table.
  2. In it's place, add the following:


  3. Save list.rhtml and refresh your browser.


  4. Reverse the sort order by adding .reverse to the end of @posts in list.rhtml:








Powered by
Movable Type 3.01D
 Feed java.net RSS Feeds