The divas talk about the new and cool features of the NetBeans IDE
Insider Scoop From the Tutorial Divas
Archives
« September 2008
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
XML
Search



Recent Entries


Links

 


Today's Page Hits: 656

Tag Cloud: ajax creator dataprovider dropdown jasperreports javaone jmaki jruby jsc jsf netbeans photohunt rails ruby table vwp
Main | Next page »
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.

Posted at 05:47PM Aug 15, 2008 in Ruby  |  http://blogs.sun.com/divas/entry/getting_started_with_netbeans_ruby1  |  Permalink  |  Comments[4]
del.icio.us | furl | simpy | slashdot | technorati | digg

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.
Posted at 10:34AM Aug 06, 2008 in Ruby  |  http://blogs.sun.com/divas/entry/netbeans_ruby_faqs_in_japanese  |  Permalink  |  Comments[1]
del.icio.us | furl | simpy | slashdot | technorati | digg

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.

Posted at 05:55PM Jul 21, 2008 in Ruby  |  http://blogs.sun.com/divas/entry/martin_talks_about_rake_runner  |  Permalink  |  Comments[0]
del.icio.us | furl | simpy | slashdot | technorati | digg

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.

Posted at 05:41PM Jul 15, 2008 in Ruby  |  http://blogs.sun.com/divas/entry/two_new_ruby_tutorials_for  |  Permalink  |  Comments[1]
del.icio.us | furl | simpy | slashdot | technorati | digg

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:

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.

Posted at 09:41AM Jul 08, 2008 in Ruby  |  http://blogs.sun.com/divas/entry/erno_talks_about_new_rails  |  Permalink  |  Comments[0]
del.icio.us | furl | simpy | slashdot | technorati | digg

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.

Posted at 04:42PM Jul 07, 2008 in Ruby  |  http://blogs.sun.com/divas/entry/how_do_i_access_databases  |  Permalink  |  Comments[0]
del.icio.us | furl | simpy | slashdot | technorati | digg

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
Posted at 03:45PM Jun 20, 2008 in Ruby  |  http://blogs.sun.com/divas/entry/using_the_irb_in_the  |  Permalink  |  Comments[4]
del.icio.us | furl | simpy | slashdot | technorati | digg

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:

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.

Posted at 10:30AM Jun 10, 2008 in Ruby  |  http://blogs.sun.com/divas/entry/my_rails_learning_path_flash  |  Permalink  |  Comments[0]
del.icio.us | furl | simpy | slashdot | technorati | digg

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:

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:

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:

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

Posted at 02:59PM Jun 06, 2008 in Ruby  |  http://blogs.sun.com/divas/entry/restful_rails_tutorial  |  Permalink  |  Comments[3]
del.icio.us | furl | simpy | slashdot | technorati | digg

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.

Posted at 11:59AM Apr 08, 2008 in Ruby  |  http://blogs.sun.com/divas/entry/see_you_at_javaone_2008  |  Permalink  |  Comments[0]
del.icio.us | furl | simpy | slashdot | technorati | digg

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.

Posted at 04:52PM Mar 26, 2008 in Ruby  |  http://blogs.sun.com/divas/entry/new_ruby_developer_resource_center  |  Permalink  |  Comments[0]
del.icio.us | furl | simpy | slashdot | technorati | digg

Monday Mar 17, 2008
NetBeans IDE 6.1 Beta Blogging Contest

I know that many of you NetBeans Ruby users blog about your experiences. Here's a chance to win a $500 gift certificate or a NetBeans T-Shirt. If you have blogged about your NetBeans 6.1 IDE experience, all you have to do is go to this Blog Contest page and submit the URL to your blog. Do it before April 18, 2008.

Posted at 05:17PM Mar 17, 2008 in Ruby  |  http://blogs.sun.com/divas/entry/netbeans_ide_6_1_beta  |  Permalink  |  Comments[0]
del.icio.us | furl | simpy | slashdot | technorati | digg

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.
Posted at 01:41PM Feb 29, 2008 in Ruby  |  http://blogs.sun.com/divas/entry/netbeans_6_1_draft_creating  |  Permalink  |  Comments[7]
del.icio.us | furl | simpy | slashdot | technorati | digg

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.

Posted at 12:06PM Jan 15, 2008 in Ruby  |  http://blogs.sun.com/divas/entry/creating_a_rails_2_0  |  Permalink  |  Comments[35]
del.icio.us | furl | simpy | slashdot |