Archive for the 'ruby-rails' Category

Campfire and AJAX making the web run faster, again

What David Heinemeier Hansson writes today links together the two latest posts I made here:

We’re currently polling every three seconds for every user active in a chat and while we’ll soon be able to regulate that between three and thirty seconds (depending on how active the chat is), it has certainly presented us with ’special needs’.

Exactly. As I wrote yesterday:

A second downside is that AJAX makes it really easy to write web pages that can hog a server much more than a traditional template processing step will ever be able to do. I can already see AJAX widgets constantly polling servers for updated data (news tickers, etc.) and possibly keeping server sockets tied for a long time, which is a usage pattern that most servers were not designed to cope well with.

So much for making the web run faster.

However, even with all this polling going on, Campfire is quite snappy and responsive. It’s really like IRC in a web browser, done right. I’m particularly intrigued by how they managed to have the browser window scrollbar scroll just the chat transcript and not the whole page. Brilliant! This is an application that really sets a new standard for web-based applications.

Campfire

campfirelogo.gifThe fine folks at 37signals have released another one of their nice, ajaxy, web-2.0-ish, ruby-on-rails applications: Campfire. Campfire is a web-based, group chat for businesses and it looks real cool.

I’m currently test-driving it and if you want to join my room for discussing Open Source, Web stuff, business opportunities or the weather in Amsterdam ;) click here.

Update: with just four available access slots in the trial version, it will be difficult to come in. Moreover, it also looks like if you close your browser window, you’ll still figure as online, thus occupying one of the slots apparently forever…

Updated update: looks like idle users get thrown out in about 90 minutes. It would be great if this interval were configurable, but at least it’s there. Good.

Technorati Tags: , , , ,

Google speaks Ruby (on Rails)

measuremap.gifDavid Heinemeier Hansson: “MeasureMap just got bought out by Google. I believe that’s the first Ruby on Rails application to be picked up in a Web 2.0′ish buyout. And it didn’t even have to launch, take that Yahoo! Speaking of, I’m now having a sale of futures in ideas for apps that I haven’t even thought of. Who’s bidding?”

Picture me envious! Here’s hoping that my Ruby on Rails application is the second one to be picked up. Yahoo! are you listening?.

Now, more seriously, Google will probably need some Ruby programmers soon so, if you have any experience, it’s maybe time to polish up your resume and send it to Google Jobs.

Last, if Measure Map is as good as they (the lucky few beta testers) say, I hope they move to an open beta soon. I don’t dislike Analytics too much, apart from the lagging issue, but having a more blog-oriented tool would rock.

Technorati Tags: , , , .

Ruby for Java Programmers, Part IV

In the previous installments of this series, I did some experiments trying to make Java and Ruby coexist by using two bridges: rjb and YAJB. This time, I’m going to try to solve the same problem using JRuby.

JRuby is not simply a bridge, it is a “1.8.2 compatible Ruby interpreter written in 100% pure Java”. As it is written in Java and consequently runs on the JVM, it should provide a much better integration. At the very least, it allows you to use some typical Ruby idioms when traversing Java collection classes, or accessing bean properties by name:

require 'java'

include_class 'Fetcher'

feed = Fetcher.fetch(ARGV[0])

feed.entries.each do | entry |
  p "#{entry.publishedDate} #{entry.title}"
end

Compare that to the sample I posted here.

You should be aware of a couple of limitations, though:

  • JRuby is not a complete implementation of Ruby. Some things are missing that, for instance, won’t allow you to run Rails on JRuby just yet. However, the development team seems to be progressing nicely along this road and supporting Rails is one of their foremost objectives.
  • Ruby extensions written in C will not be loaded. This is probably never going to change. If you need a particular C extension, you should try to find an alternative in pure Ruby or Java.

Ruby for Java Programmers, Part III

Just tried to perform the same test I did in Part II using YAJB instead of rjb. Unfortunately, I wasn’t able to obtain any result, since even a simple program like:

require 'yajb/jbridge'
include JavaBridge
jimport "java.io.*"

fails with a java.lang.OutOfMemoryError. This is on OS X 10.4, YMMV.

Ruby for Java Programmers, Part II

Part I is here.

As promised, I will now try to invoke some more complex Java classes from Ruby code. Since I might need this for a real project and one of the things I find missing in Ruby is an RSS/Atom parser that offers the same features as Rome, I figured I might just try fetch and parse an RSS feed using Rome via Ruby.

Even something simple as fetching a single feed using Rome involves a handful of classes and methods. If all you need is getting at feed entries from your Ruby code, you’d be much better of if you encapsulate API calls in some higher-level class that is intended to be called from Ruby. This will avoid you the hassle of importing more than one class and calling overridden methods for which you’ll have to supply signatures and such trivia. This is just what I did in Fetcher.java:

import java.net.URL;
import com.sun.syndication.feed.synd.SyndFeed;
import com.sun.syndication.fetcher.FeedFetcher;
import com.sun.syndication.fetcher.impl.FeedFetcherCache;
import com.sun.syndication.fetcher.impl.HashMapFeedInfoCache;
import com.sun.syndication.fetcher.impl.HttpURLFeedFetcher;

public class Fetcher {
	public static SyndFeed fetch(String url) throws Exception {
		URL feedUrl = new URL(url);
		FeedFetcherCache feedInfoCache = HashMapFeedInfoCache.getInstance();
		FeedFetcher fetcher = new HttpURLFeedFetcher(feedInfoCache);
		SyndFeed feed = fetcher.retrieveFeed(feedUrl);
		return feed;
	}
}

Calling this class from Ruby is straightforward enough:

require 'rjb'

Rjb::load('.:rome-0.7.jar:rome-fetcher-0.7.jar:jdom.jar:jdom.jar', [])

fetcher = Rjb::import('Fetcher')
feed = fetcher.fetch(ARGV[0])
p feed.getTitle
entries = feed.getEntries.iterator
while entries.hasNext do
    entry = entries.next
    p "#{entry.getPublishedDate.toString} #{entry.getTitle}"
end

Two things to note here. First, it would be great if the Ruby-Java bridge would pick up JavaBeans conventions and allow you to simply write entry.title instead of entry.getTitle.

Second, I will probably need to convert Java dates to Ruby Time objects by formatting as a string and then parsing it back. It would also be useful if the Ruby-Java bridge could provide more automatic type conversions, where such convertions are possible, besides simple strings.

Ruby for Java programmers, Part I

This is the first article in a series that I plan to write in order to describe my experiments with combining together Ruby and Java. The reason I’m doing this is that, as much as I find Ruby on Rails to be fun and agile and all-around great, still I haven’t grasped much of Ruby the language yet, so I sometimes find myself wanting to reuse some Java code (and there’s a helluva lot of it around, free for grabs) instead of thinking about a rewrite.

One of the things I’d really want to be able to do is call Java code from Ruby. There are some projects intended to provide a Ruby-to-Java bridge, even though none of them seems to be really mature. The ones I found mentioned more often seem to be RubyJavaBridge and YAJB.

Let’s start with the former. After downloading and unzipping the file, you should read the provided readme.txt file, as there don’t seem to be instructions on the website for actually performing the build. If you’re under OS X, make sure the JAVA_HOME environment variable is set (should be something like /Library/Java/Home, unless your setup is peculiar). Also, ignore everything about the LD_LIBRARY_PATH variable, again if you’re on OS X.

Then you can try configuring and compiling the sources with:

    ruby setup.rb config
    ruby setup.rb setup

On OS X, this will fail, as the off_t type is used but never declared. I assume it gets defined in one of the included C header files in Linux and Windows, but under OS X it’s to be found in <sys/types.h>, which is not included. You can fix it by adding the following statement:

#include <sys/types.h>

to file ext/rjb.h, around line 25 should be fine. After this, everything should compile and install fine just by following the instructions.

Next I did a series of tests with simple Java types to confirm that the JVM was loaded and that the basic functionality of the bridge was fine. In the coming days I plan to invoke some more complex library and report my findings in further installments of this series.

Google: Evil or Not?

Do you still believe the “Do no evil” Google mantra? Do you think Google Book Search, the AOL deal, and Larry and Sergey’s 767 point to Google losing it’s pristine morality and turning over to the dark side?

Now you can discover what the world thinks and contribute your own opinion. Head over to Google: Evil or Not? and vote with your mouse. Every day, the site presents you with a selection of relevant news snippets and, for each one of them, you can select the level of Google evilness, or lack thereof, that is suggested by it. Let the collective wisdom of the Web decide whether Google is evil or not!

Alright, it’s a silly little app, but it could be fun. It’s also my first application developed with Ruby on Rails and it’s fully Web 2.0 compliant, uses RSS and Ajax and leverages the power of the community. What more could you ask? ;)

Book review: Agile Web Development with Rails

Agile Web Development with Rails, by Dave Thomas, David Heinemeier Hansson.

Book coverRails, or more appropriately Ruby on Rails is the new web application development framework that everyone is so excited of and raving about how it cuts development time by a factor of 10 and does away with the cumbersome XML configuration files that are the hallmark of J2EE.

Being an old Java hand, I wanted to see firsthand if there was some substance beneath all the hype. I was also intrigued by the fact that many other old Java hands whom I respect and admire, like James Duncan Davidson, Elliotte Rusty Harold, Bruce Tate, Graham Glass, and Brian McAllister are now fervent (to different degrees) rubyists and Rails-enthusiasts. If it weren’t for them, I would never have undertaken this journey, probably.

But anyway, this is supposed to be a book review, not a chronicle of my ongoing discovery of Rails.

I mostly like using books to discover and learn about new technologies, so it’s perfectly natural that I decided to take off with what is considered the book about Rails. And how could it be not, with Rails’ creator David Heinemeier Hansson as one of its authors?

It is also the only one published so far but, even though the choice was a bit, uhm … limited, I wasn’t disappointed. The book, as is customary with titles from The Pragmatic Programmers’ bookshelf, is very good. It lays down in detail almost everything you need to know to be productive with Rails, save for the language Ruby itself. To be honest, the book includes an appendix introducing the basics of Ruby, but it’s just the bare minimum. I suggest getting yourself a good Ruby book (like Programming Ruby, also from The Pragmatic Programmers, which I am currently reading and will review shortly) if you really want to get the most out of Rails.

Another caveat you have to be aware of is that Rails is a quickly moving target. The book covers version 0.13, which was current around mid-2005. There was a 0.14 version after that and we are now at 1.0, since a few weeks ago. However, I didn’t find I had much to change while experimenting with Rails following the book. As always with Open Source software, resorting to the mailing lists, forums or the #rubyonrails@freenode.net IRC channel is the best avenue for finding answers to your doubts and asking support questions.

The book is organized in four parts:

Part I introduces the design principles behind Rails, its most important concepts and briefly covers how to get started by installing it and writing your first program. The part about installation is the one that is bound to become quickly obsolete, as new and easier installation methods for the various supported platforms are developed.

Part II dives into Rails by guiding you along the development of a real (albeit much simplified) e-commerce application. I find this approach to be very good and “pragmatic” indeed. Of notable interest is the chapter on testing. It’s great to see that providing a good test scaffolding was one of the main design concerns in Rails and not just an afterthought.

Part III goes deeper into Rails and can be used as a reference for its components, like Active Record, Action Controller, and Action View. Bonus chapters on AJAX, Web Services, security, deployment and scaling issues are included here and will make the book even more valuable when you need to deal with “real world” applications.

Part IV contains the appendices, like the above mentioned introduction to Ruby, a reference of configuration parameters (be warned again: these might change), the full source code for all samples (of dubious value, in my opinion), and a list of online resources (once again, a list bound to be more and more incomplete as time passes and the excitement around Rails grows).

Overall, I find the quality of this book to be excellent. It’s not thick to the point of being too heavy to carry around in your laptop bag, for those times when you need to peek at it, yet it covers enough of Rails to be considered a complete and authoritative reference. This is probably a testament to Rails’ simplicity too.

The writing style is eminently readable. You can read it cover to cover, if you like, without getting bored. The frequent sidebars make it lively without being too distracting. A great amount of care and craftsmanship went into producing this book, and it shows.

Highly recommended!

On Rails

On the trainNo, this post is not about Ruby on Rails (they just released version 1.0, by the way), but it’s half about rails, as in “railways”, and half about Ruby the language.

With respect to the former, I was finally able to book my railway trip to Rome, despite my previously reported problems. I enjoyed traveling by train much more than traveling by plane. It’s true that it takes more time, but when you compare having to wait in line at the check-in counter, at the security control, at the gate, at the plane door, then traveling for one hour in a crammed space and finally having to wait for your luggage, to sitting quite comfortably for four hours, at half the price, the choice is clear.

Ruby die-hards might comment that the experience of traveling by plane is akin to programming in Java, which brings us to the second half of this post. While traveling, I did a bit of Ruby programming, just for fun. One thing that struck me negatively about Ruby is learning that Ruby strings are made up of 8-bit bytes. Uh-oh, I smell trouble ahead. Indeed, I hit trouble as soon as I tried to parse (using Lucas Carlson’s SimpleRSS library) some RSS feeds that used different encodings (UTF-8 vs. ISO-8859-1, for example). If I were using Java and a Java XML parser, I’m pretty sure that the strings containing the text values extracted from the feed would have all been Unicode string and I would have had no problems mixing them or storing them in a UTF-8 encoded database.

I’m pretty sure this problem is mostly due to my ignorance of Ruby, but still I wonder whether using 8-bit characters in the era of globalization was a wise decision. I’d rather have Java’s 16-bit characters, if possible.

Update: Got it to work by determining the original encoding using open-uri’s charset method and iconv to convert between it and UTF-8. Suboptimal, but it works.

Hani bileblogs Basecamp

I’m surprised to see that David Heinemeier Hansson took offense at
the latest BileBlog:

This is awesome. In the sense of awesome meaning funny in a sad, tragic way where you feel sorry for the person.

It’s surprising that David fell for Hani’s prank, just like an ordinary Andy C. Oliver. Know what, David? Hani’s biles are the self-inflicted punishment that we Java-types deserve for our sins, like XML configuration files, EJB and all the JCP madness. We enjoy them just like Xians enjoy being punished for their sins. It’s all guilt.

Note for the humor-impaired: the above was largely ironic. However, there’s also some serious debate material in this thread, buried under all the mudslinging. We can start from the following Hani quote:

There’s no doubt that ajax, tagging, semantic fappery and all that other gibberish have some potential. Ultimately though, there is no revolution, nor even an evolution. It’s simply the ability to toss in a few more tools in the toolbox. Specialised tools, that can be effective when used against the right obstacle.”

Ruby on Rails: First contact

rails_logo_remix.gifToday I finally decided to dive a little into Ruby on Rails. I have a cool, small and fun application in mind and wanted to see whether it’s true that Rails is so much more productive that I could develop it in my very little free time.

Being on OS X Tiger, first of all I had to fix Ruby following these instructions. Then, to make things easier, I decided to download and install Locomotive. I started Rails, generated a simple controller and wrote my first “Hello world” webapp. So far, so good.

My first attempt to generate a scaffold didn’t go too well. Looks like there’s a bug in Rails 0.14.1, the version included in Locomotive. I applied this patch and everything was fine again.

From here, the plot started to thicken. The table for which I wanted to generate a scaffold had a few fields named xx_count and these columns were not mapped by ActiveRecord. By sheer luck, and after some head scratching, I guessed that it didn’t like the column names. I changed them to xx_cnt and it worked! Go figure.

I am also accustomed to putting an integer field named id in my tables and to use it as a primary key. Fortunately, this is exactly the type of pattern that Rails is most happy with. The only problem is that, being a hater of MySQL, I configured Rails to connnect to my PostgreSQL 8 server from the start (Locomotive supports MySQL, PostgreSQL and SQLite out of the box). Since Rails wants the id field to be auto-incremented by the database and PostgreSQL does not support the serial column type, I got some cryptic errors upon trying to save a new record. The messages could have been much more explicit, but I could have figured it out earlier, had not my clarity of vision been obfuscated by a long work day.

Anyway, Google to the rescue, I worked around this problem following the suggestion outlined here, and I was finally able to get a basic CRUD application working. Next time, I’ll try to start implementing some more realistic use case. To be honest, I haven’t yet figured out the details of how my app is supposed to work and look like. I think I’ll just code away and see what comes out of it, testing various solutions along the way and seeing what sticks. I hope that, with Rails’ purported high productivity, I won’t regret too much ending in a cul-de-sac and having to start over again. I’m mostly doing this for fun and for learning, so errors are a good, actually.

Another migration to Rails

headshot.jpgAfter Graham Glass, here comes another old Java hand diving into Ruby on Rails.

Elliotte Rusty Harold: “I tried writing some PHP pages, but that was more difficult than I expected so I thought I’d take a day and see if Ruby on Rails was all it was cracked up to be. I’d looked at it initially, but decided against it because IBiblio doesn’t yet support Ruby. But I’m prototyping this on my desktop Mac, and if Ruby makes my job a lot easier, I could find a different host.”

I will follow this development with lots of attention, but already the following snippet raised my alarm sensors:

It’s trying to set a cookie for no reason whatsoever, even for a page that doesn’t exist! What’s worse, it’s a session ID! This is completely contrary to the web architecture, and a very common mistake made by developers who are mired in 1980s style of applications and have never understood the Web, and probably never will. My PHP version and the existing site I’m replacing are completely cookie-free. This is not a good sign, and does not leave me with a warm-and-fuzzy feeling; but let’s deny the setting of the cookie, proceed onward, and see what happens.

Can this be true? I’d like to know. Looks like this will be soon, as while I was writing this the bell rang: It’s my new Ruby and Rails books! Looks like my productivity might drop just a little bit in the coming days ;).

Tempted by Rails

rails_logo_remix.gifI’m really starting to think that I need to freshen my development skills. Even after many years of programming, becoming more and more of an architect (whatever that means) does not imply that one should stop coding or learning new languages and techniques.

One of the most intriguing new languages is of course Ruby and its amazing (according to most observers) Rails web application framework. Being reassured that such a simple technology is not simplistic and can compete with complex J2EE servers in terms of scalability and reliability is comforting:

Jon Tirsen: “For a production management system of this caliber in J2EE you would pay hundreds of thousands of dollars and the cool thing is that SwitchTower actually has features not even the big iron appservers managed to implement. SwitchTower allows for pretty much complete 24/7 including completely seamless upgrades (and rollbacks) where the user wouldn’t even loose the session. How could the Rails team pull this off when companies like BEA and IBM never did regardless of how many millions of dollars and manyears of effort they’ve poured into their software?”

What is still holding me back is the fact that, by choosing Java for my next project, I am not just choosing a language and a platform, but also an incredible amount of libraries, frameworks and toolkits. For most problems you will be facing while developing a Java application, there is probably some library out there that solves it brilliantly, is Open Source and good quality too.

Case in point: I am a big fan of the “Search, Don’t Sort” approach and whenever I need to add a search feature to my apps (which happens almost always) I know I can use Lucene, which is real good. Or I can use Rome for reading and publishing RSS/Atom feeds, as I did recently. And having an RSS feed is the hallmark of any decent Web 2.0 (sorry, Joel) application, right? ;)

So, the only thing that worries me a little is: will I still be able to tap a comparable reservoir of code when I implement my next Web application with Ruby on Rails? Just wondering.

Update: later today, Brian McCallister announces:

David Balmain has released Ferret unto the world. Ferret is one of the most requested libraries I have seen for ruby — a native port (not a gcj and bindings!) of Lucene!