Tuesday Apr 08, 2008
Tuesday Apr 08, 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
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
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.
This tutorial requires the following technologies and resources.
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.
rubyweblog in the Project Name text box.
Accept all the other default settings on this page.
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.
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.
In the Projects window, right-click the rubyweblog project node and choose Generate.
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).
Post in the Model Name text box.
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.
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.
Rake creates the MySQL database for the development configuration in the database.yml file.
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
|
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.
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"
map.root :controller => "posts"
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.
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.
Click the New post link to display the second page of the application.
Enter a title and click Create.
Click the Back link to return to the list of posts.
Here you add a body column to posts table to hold the text for each blog entry.
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
|
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.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 %>
|
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 %>
|
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 %> |
Return to the browser and click the New Post link to see how Ruby recognizes the new body column.
Create a few more blog entries.
Here, you add code to the Post class to ensure that the users provide values for both the title and the body fields.
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
validates_presence_of :title, :body
Run the application, click New Post, and click Create.
The application now reports that the title and body cannot be blank.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.
Save the changes and run the application to see the new interface for the Post model.
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| %>
Friday Dec 14, 2007
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.)
<%= jmaki_widget 'yahoo.dataTable',
:value =>
{:columns => [
{ :label => 'Id', :id => 'id'},
{ :label =>'Type', :id => 'type'},
{ :label => 'Price', :id => 'price'},
],
:rows => @items
}
-%>
|
Tuesday Dec 04, 2007
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.
So, how do you Ruby? Got a nugget to share? We would love to hear from you.
Friday Nov 30, 2007
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.
Tuesday Nov 27, 2007
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
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.
Tuesday Nov 13, 2007

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
You also might want to check out the Swing with JRuby: Developing a Desktop Application with the JRuby and Java Swing APIs tutorial that was written by Sun campus ambassador Teera Kanokkanjanarat.
Wednesday Nov 07, 2007
The other day, Tor Norbye sent us an email listing some NetBeans Ruby navigation shortcuts, which we thought we'd highlight in the blog. We did a little further research on the subject and also list here some favorite user shortcuts that we undercovered.
(For a complete list of NetBeans Ruby Keyboard Shortcuts, see Ruby Shortcuts).
Navigation Shortcuts
Navigation is important - jumping between files and their tests, or between Rails actions and views. Here are some navigation shortcuts:
User Favorite Shortcuts
Here are some more frequently used shortcuts.
| Action | Shortcut | Mac Shortcut |
|---|---|---|
| Show code completion alternatives | Ctrl-Space. If Ctrl-Space does not work for your language, try using Ctrl-\ | Ctrl-Space |
| Open File by name prefix (not path) | Alt-Shift-O | Ctrl-Shift-O |
| Show name of current parameter (when editing an argument list for a method call) | Ctrl-P | Command-P |
| Format Code | Alt-Shift-F | Ctrl-Shift-F |
| Reformat the current comment paragraph | Ctrl-Shift-P | Command-Shift-P |
| Jump to matching parenthesis / brace / bracket, or other matching | Ctrl-[ | Command-[ |
| Show Documentation | Ctrl-Shift-Space | Command-Shift-Space |
NetBeans Shortcuts
You can download a shortcut card that lists the highlights of the NetBeans IDE 6.0 keyboard shortcuts and code templates. In the NetBeans IDE, choose Help > Keyboard Shortcuts Card from the main menu. Similarly, you can view the shortcuts online from the NetBeans IDE 6.0 Keyboard Shortcuts Specification.
Friday Nov 02, 2007
Teera Kanokkanjanarat is a Sun campus ambassador who recently contributed the tutorial Swing with JRuby: Developing a Desktop Application with the JRuby and Java Swing APIs. Here we interview Teera to find out more about his interest in NetBeans Ruby.
First, tell us a little bit about yourself.I've been working as a freelance software developer for about 8 years ever since finishing high school. My work mainly focuses on the web platform with various technologies ranging from Java, ASP.NET, PHP, and recently I got started on Ruby and Rails. Since November 2006, I've been hired by Sun as a campus ambassador at Simon University in British Columbia, Vancouver, where I'm completing my degree in Computing Science and Business Administration.
What is your interest in Ruby?
Coming from the strongly-typed language world of Java and C#, I find the flexibility and dynamic of the Ruby language to be very interesting. I believe that the productivity of developers has a heavy impact on the cost of software projects. I often find that I waste time waiting for the project to compile and re-deploy to web or application servers. So that's the first thing I found really appealing when I started working with the Ruby and Rails framework. Ruby seems to gain a lot of momentum on the web platform with the Rails framework. Now I'm more interested in the future of Ruby as a rich client on the desktop.
How did you learn Ruby?
I started out on Hal Fulton's The Ruby Way book to learn the Ruby language itself and the Ruby way of doing things. I often watch screencasts and vodcasts for techniques on learning Rails. I'm also a member of the Vancouver Ruby and Rails user group, where I attend monthly meetings. This is an interesting group; as a Java guy, I learn so much from others who work with Ruby on a daily basis.
What do you like and dislike about Ruby?
The Ruby language itself is beautiful. There are not many programming languages that are as intuitive and give me that "wow this is cool stuff!" sort of thrill. Of course, this is also because of Ruby's coding conventions and key principles.
I actually did a small experiment re-creating one of my old, small Java-based web projects with Ruby on Rails. I found that the entire project on RoR actually contains fewer lines of code than that in the previous version's configuration files!
In my opinion, performance and deployment are still the key issues of Ruby. JRuby and other initiatives are really aiming on these two issues.
How has NetBeans helped you build Ruby apps?
I tried RadRails, TextMate, and InstantRails. Yet, I like Netbeans Ruby support the most, especially in code editing, the Ruby debugger, and the auto-complete capability. Netbeans is tightly integrated with JRuby as well.
Tell us about the NetBeans Ruby app you are currently building?
I'm developing JSF web components for one of the my clients. There's future planning to release these components in rich client version (Swing and SWT). I'm doing an experimental project on how to leverage JRuby for developing these desktop components.What was your favorite experience as a Sun ambassador?
Meeting with people! I made a lot of friends from around the world through this program. I also learned a lot from talking to people when I do evangelizing work, whether it's a tech demo or a presentation at a user group. Nothing beats learning from those who do real work out there in the field.
What are some things you like to do outside school and work?
I started a small coffee shop back when I was 19 and opened up a day-spa with my sister about two years ago. Both of them are in Thailand. So, I'm helping my sister run them remotely.
Where do you see yourself in five years?
Completing my degree is my first priority (it has been delayed several times due to my work). After finishing my term at Sun at the end of this year, I'll be joining Business Objects as a software developer. In the next five years, I might do another startup if there some good ideas come along, but things change, you never know.
Tuesday Oct 30, 2007
We have posted a draft of the first 2 sections of the Getting Started With Ruby and Rails tutorial. If you can take some time to look it over and give us feedback, please do.
For those of you who are new to using the NetBeans Ruby support, we would like to know:
For those of you who are experienced with Ruby, can you look for incorrect terminology or misinformation? Are the code examples ok?
To provide feedback on this tutorial, please send corrections, suggestions, and comments to the NetBeans Ruby Developers mailing list at dev@ruby.netbeans.org. Put "Getting Started Draft Feedback" in the subject line.
Monday Oct 29, 2007
In this blog, we would like to acknowledge two NetBeans Ruby community-contributed tutorials:
Thanks to Teera and Amit, we have a richer documentation set, which you can view in its entirety on the NetBeans Ruby Tutorials and Screencasts page.
If you are interested in contributing documentation to the NetBeans Community, consider joining the dev@userguide.netbeans.org email alias. This alias is for community members who want to not only contribute documentation but also provide input and feedback regarding existing NetBeans documentation. You can sign up for the alias as follows:
Friday Oct 19, 2007
Next week (October 22 - 26) you will have the opportunity to submit written questions about all things NetBeans to a team of NetBeans evangelists, including Ruby technology evangelist Brian Leonard.. You can submit a question any time during that week, and the evangelists will try to answer as many questions as possible. They will also post a selected set of questions and answers. To learn more, visit the Ask the Experts events page.
Monday Oct 15, 2007
I have written both an installation and configuration article and an accessing databases FAQ for projects built using NetBeans Ruby support. However, because there are lots of different configuration paths, and each path requires some in-depth information, neither of these documents make it easy to quickly figure out what you must do to set up your Rails project to access your database server. I created this chart to hopefully make the steps simpler, and more clear. If you need more details, then consult the two documents that I mention above.
| Steps for Accessing Databases Using NetBeans Ruby Support | |||||||||||||||||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
|
|||||||||||||||||||||||||
|
|||||||||||||||||||||||||
|
All |
|||||||||||||||||||||||||
| Do: Edit database.yml to specify username, password, and, if necessary, database name. | |||||||||||||||||||||||||
Wednesday Sep 26, 2007
The jMaki 1.0 framework, with support for Java, PHP, and Ruby, was released yesterday. Last week, Arun Gupta posted a screencast showing how to use jMaki wrappers of button and table widgets from Dojo and Yahoo frameworks in a Ruby on Rails application built using the NetBeans 6.0 Beta IDE.
With Arun's permission, I am supplying the steps to recreate a similar jMaki on Rails project. To save steps, I changed the order a bit. If you don't already have NetBeans Ruby Support, go to the Installing and Configuring Ruby Support tutorial for instructions.
mysqladmin -u root -p create rorjmakitables_developmentIf you don't need a password, omit the -p.