To ensure your test cases call efficient MySQL

  def test_my_case
    assert_efficient_sql do

      # just wrap them in this block!

    end
  end

The assertion intercepts and copies out your MySQL SELECT statements, then calls EXPLAIN on each one, and inspects the results for common problems.

The goal is test cases that resist database pessimization, even as you change your data relations, to add new features. If you run your tests after every few changes, you can easily detect which change broke your database’s indices and relations.

This article is a reference for this assertion’s options. The techniques should be ported to any database with an EXPLAIN or similar system.

Gregory Brown

If you don’t mind ‘bad’ language and a little bit of hate, go check out Zed Shaw’s rant,Rails is a Ghetto.

I’m not quite sure what his intent was with the article, I’m not sure that even matters. What I know is that it has shock value, it made me laugh, and that a number of things in it ring true with me, even if a bit magnified.

Zed and I have had at least a couple conversations about the Ruby / Rails communities before, and I’d say philosophically, we’re mostly on the same page. The key difference is that Zed is… umm… Zed.

One thing that he pointed out as a difference between us is that I don’t really challenge the status quo. This is true, I prefer to slowly bend the rules rather than shatter them, and see where that takes me. My response though was that I like to challenge the folks who try to suppress those who would challenge the status quo.

So here’s my challenge at a few responses, because everyone loves to stir things up!

Zed is so Ghetto:

However, such a hate-filled nasty person should not be allowed to terrorize the nice, pleasant, and generous Ruby community. Sure there are bad guys out there, there are in any community, but this type of rant is pure crap. Such arrogance and hate are self-destructive. I hope Zed’s self-destruction happens far away from my world, but I wish it would hurry up so the rest of us can get back to enjoying writing code.

Wait a second. Zed is getting in the way of you enjoying writing code? Is Zed Shaw standing there threatening Roundhouse kicks to the head while you try to type in some Ruby code?

Or is Zed distracting you because you’re reading his blog and getting offended? If so… it seems that the solution is the same as if you don’t like something on TV. Change the channel. Go outside and take a walk.

Wear some garlic, I heard Zed hates garlic. Something about how it steals his magic powers.

On a serious note though, saying that hating on people in public is self destructive is like saying that smoking crack is self-destructive. If you think that Zed doesn’t know what he’s doing, you’ve been duped.

I was going to go on and challenge a few more of Zed’s haters. But you know what, I haven’t found any. The closest thing is Giles Bowkett being concerned about how anger is bad for Zed’s heart. There was also something from a consulting company which mostly agreed with Zed’s points, with only minor disagreements.

I’m not defending Zed. As you can see from the posts, he’ll physically defend himself if need be, so he doesn’t need that. I’m also not much of a fanboy, I like mongrel but I can remember when it was just something we were chatting about and playing with at NYC.rb. Still, the real thing that I’d like to confirm here is that he has a point.

If the Ruby community starts to get up in arms when they see rants like this, that’s even more of an indication of the fact that the lines between the Ruby and Rails communities have blurred, and that we’re going to increasingly turn away our best hackers who are interested in real community, beginning a slow slip all the way to JavaOne.

The good news of course is that Technorati lists a number of links to Zed’s rant with comments like “entertaining”, “hilarious”, and other such praises. Every strong community needs heroes and anti-heroes. My question is only who will replace Zed.

Gregory Brown

Some of you may know that I’ve been working on The Ruport Book, a free-content book about Ruby Reports. Mike Milner and I have really learned through trial by fire some of the pros and cons of DIY technical publishing in the last few months. I’d like to share some of my thoughts here in a mini-ramble in hopes of stirring up conversation and ideas.

Got a favorite gem you want to tell the world about? Or one you want to warn other people about? You can do both with Gemtacular!

Gemtacular (http://www.gemtacular.com) is a place to rate and review Ruby gems. It’s a great place to not only find opinions on various gems, but also to see the most recent gem uploads, find the most highly rated gems, or just search for existing gems.

Some quick guidelines:

* Gemtacular is not a place to report bugs. Use the project page for that.
* Be nice. If you have a problem with a particular gem, please explain why without getting nasty.
* Don’t be lame and rate your own gems.1

1I already have a feature request in to try and prevent this at http://rubyforge.org/tracker/index.php?func=detail&aid=10063&group_id=2863&atid=11067

Gregory Brown

The most important thing I’ve picked up with each RubyConf I’ve attended is a new outlook on my work. Each year the talks invite people to have their minds bent a bit, both technically and philosophically. Though I didn’t take notes and my attention span is usually too low to keep a full talk in my head, the following discussion is largely based on ideas from various talks I attended, especially from Nathaniel Talbott, Eric Hodel, Ryan Davis and Evan Phoenix. It also has some sprinklings from the hallway track, as well as some delusions from the back of my mind. Sorting all that out is up to you.

So what is real productivity? Maybe we can look at it as the coding nirvana that we’re all striving for, but I think it’s even more simple than that. True productivity just involves eliminating apathy from your life, leaving you with nothing left but things you care about, and no choice but to take care of them. What follows is a simple extension of that general idea into software practices.

Did you know you can do this with Ruby out of the box?

# A real lambda
λ { puts ‘Hello’ }.call => ‘Hello’

# Sigma - sum of all elements
∑(1,2,3) => 6

# Square root
√ 49 => 7.0

How difficult was this to implement? Keep reading!

Timothy M. O

Via ComputerWorld:

“Leopard also offers a veritable playground for developers, with Ruby on Rails, Mongrel and Capistrano all baked into the operating system. Developers also get DTrace, which is built into the operating system’s core, allowing developers to observe, debug and tune applications in real time.”

I guess that also implies that it comes with RubyGems baked in? (Apologies for the shameless Mac-touting and link blogging.)

Timothy M. O

Check out Ola Bini’s blog: Updated JRuby on Rails performance numbers. Excerpt:

…we are talking about 9.5s MRI to 13.8s for JRuby, which I find is a quite nice achievement if you look at the numbers from Friday. We are inching closer and closer. Both the view and the controller numbers are looking very nice. This is actually indicative of a nice trend - since general JRuby primitive performance is really good, the slowness in our Regular Expression engine is weighed up by much faster execution speed.

JRuby/MRI seems to be the metric that Ola’s focused on: his numbers give a ratio of 1.45 for Rails Petstore (13.8/9.5) on October 16th.

Take a look at this post to JRuby’s Dev list on Oct 4th from Christian Seiler: “JRuby vs MRI - Petstore shootout”. In it he charts the improvement between JRuby revision 4383 (sep 25th) and 4470 (early oct). And he demonstrates about a 20% performance improvement between those two revisions. On October 4th jRuby/MRI was 1.565 for Rails Petstore (29.89/19.10).

C. Nutter is also focused on Performance Updates.

This is a short followup to my last post where I compared library RubyForge statistics against CPAN. This week I compare RubyForge against…the Ruby Application Archive!

Yes, I know, the RAA is just a listing service and RubyForge is not. That’s not the point. Please read on.

Gregory Brown

Anyone else think that Godwin’s Law should be amended to include Rails?

Just a thought.

UPDATE (2007.09.27): Several have pointed out that Godwin’s Law isn’t the precise thing that should be updated. Really it’s Case’s Corollary that needs to be changed, thanks for helping me realize this.

Derek Sivers

SUMMARY: I spent two years trying to make Rails do something it wasn’t meant to do, then realized my old abandoned language (PHP, in my case) would do just fine if approached with my new Rails-gained wisdom.

INTRO / BACKGROUND:

Back in January 2005, I announced on the O’Reilly blog that I was going to completely scrap over 100,000 lines of messy PHP code in my existing CD Baby (cdbaby.com) website, and rewrite the entire thing in Rails, from scratch.

I hired one of the best Rails programmers in the world (Jeremy Kemper aka bitsweat), and we set off on this huge task with intensity. The first few months showed good progress, and Jeremy could not have been more amazing, twisting the deep inner guts of Rails to make it do things it was never intended to do.

But at every step, it seemed our needs clashed with Rails’ preferences. (Like trying to turn a train into a boat. It’s do-able with a lot of glue. But it’s damn hard. And certainly makes you ask why you’re really doing this.)

Two years (!) later, after various setbacks, we were less than halfway done.* (To be fair to Jeremy’s mad skillz: many setbacks were because of tech emergencies that pulled our attention to other internal projects that were not the rewrite itself.) The entire music distribution world had changed, and we were still working on the same goddamn rewrite. I said fuckit, and we abandoned the Rails rewrite. Jeremy took a job with 37 Signals, and that was that.

I didn’t abandon the rewrite IDEA, though. I just asked myself one important question:

“Is there anything Rails can do, that PHP CAN’T do?”

The answer is no.

I threw away 2 years of Rails code, and opened a new empty Subversion respository.

Then in a mere TWO MONTHS, by myself, not even telling anyone I was doing this, using nothing but vi, and no frameworks, I rewrote CD Baby from scratch in PHP. Done! Launched! And it works amazingly well.

It’s the most beautiful PHP I’ve ever written, all wonderfully MVC and DRY, and and I owe it all to Rails.

Inspired by Rails:

*- all logic is coming from the models, one per database table, like Martin Fowler’s Active Record pattern.

*- no requires or includes needed, thanks to __autoload.

*- real MVC separation: controllers have no HTML or business-logic, and only use REST-approved HTTP. (GET is only get. Any destructive actions require POST.)

*- all HTML coming from a cute and powerful templating system I whipped up in 80 lines, all multi-lingual and caching and everything

*- … and much more. In only 12,000 lines of code, including HTML templates. (Down from 90,000, before.)

Though I’m not saying other people should do what I’ve done, I thought I should share my reasons and lessons-learned, here:

SEVEN REASONS I SWITCHED BACK TO PHP AFTER 2 YEARS ON RAILS:

#1 - “IS THERE ANYTHING RAILS/RUBY CAN DO THAT PHP CAN’T DO? … (thinking)… NO.”
For 2 years, I thought Rails is genius, PHP is shit. Rails is powerful, PHP is crap.
I was nearly killing my company in the name of blindly insisting Rails was the answer to all questions, timeframes be damned.
But when I took a real emotionless non-prejudiced look at it, I realized the language didn’t matter that much.
Ruby is prettier. Rails has nice shortcuts. But no big shortcuts I can’t code-up myself in a day if needed.
Looked at from a real practical point of view, I could do anything in PHP, and there were many business reasons to do so.

#2 - OUR ENTIRE COMPANY’S STUFF WAS IN PHP: DON’T UNDERESTIMATE INTEGRATION
By the old plan (ditching all PHP and doing it all in Rails), there was going to be this One Big Day, where our entire Intranet, Storefront, Members’ Login Area, and dozens of cron shell scripts were ALL going to have to change. 85 employees re-trained. All customers and clients calling up furious that One Big Day, with questions about the new system.
Instead, I was able to slowly gut the ugly PHP and replace it with beautiful PHP. Launch in stages. No big re-training.

#3 - DON’T WANT WHAT I DON’T NEED
I admire the hell out of the Rails core gang that actually understand every line inside Rails itself. But I don’t. And I’m sure I will never use 90% of it.
With my little self-made system, every line is only what’s absolutely necessary. That makes me extremely happy and comfortable.

#4 - IT’S SMALL AND FAST
One little 2U LAMP server is serving up a ton of cdbaby.com traffic damn fast with hardly any load.

#5 - IT’S BUILT TO MY TASTES
I don’t need to adapt my ways to Rails. I tell PHP exactly what I want to do, the way I want to do it, and it doesn’t complain.
I was having to hack-up Rails with all kinds of plugins and mods to get it to be the multi-lingual integration to our existing 95-table database.
My new code was made just for me. The most efficient possible code to work with our exact needs.

#6 - I LOVE SQL
Speaking of tastes: tiny but important thing : I love SQL. I dream in queries. I think in tables.
I was always fighting against Rails and its migrations hiding my beloved SQL from me.

#7 - PROGRAMMING LANGUAGES ARE LIKE GIRLFRIENDS: THE NEW ONE IS BETTER BECAUSE *YOU* ARE BETTER
Rails was an amazing teacher. I loved it’s “do exactly as I say” paint-by-numbers framework that taught me some great guidelines.
I love Ruby for making me really understand OOP. God, Ruby is so beautiful. I love you, Ruby.
But the main reason that any programmer learning any new language thinks the new language is SO much better than the old one is because he’s a better programmer now! You look back at your old ugly PHP code, compared to your new beautiful Ruby code, and think, “God that PHP is ugly!” But don’t forget you wrote that PHP years ago and are unfairly discriminating against it now.
It’s not the language (entirely). It’s you, dude. You’re better now. Give yourself some credit.

Ok. All that being said, I’m looking forward to using Rails some day when I start a brand new project from scratch, with Rails in mind from the beginning.

But I hope that this reaches someone somewhere thinking, “God our old code is ugly. If we only threw it all away and did it all over in Rails, it’d be so much easier!”

It’s often been said that Perl’s greatest strength is CPAN, Perl’s vast collection of free libraries contributed by developers from around the world. Recently I started to wonder about RubyForge and how RubyForge stacks up against CPAN in general.1

Gregory Brown

This year is a good year for Ruby on the east coast. We kicked things off with a bang with the Gotham Ruby Conference in April, saw the Ruby Hoedown come and go in Raleigh bringing along with it some great videos of their talks, and of course, will see the Seventh International RubyConf in Charlotte in just a couple months.

However, these aren’t the only games in town. We’ve also got Ruby East 2007, which is a one day, multi-track, Rails friendly regional conference at the Penn State Great Valley Campus. They’ve managed to get an impressive list of speakers together, and even let two of those vagabonds from the Ruby Reports project sneak in to do their ranting.

If you’re local to the area and don’t think you’ll make RubyConf this year, this is a good chance to still get your fix. If you’ve been tinkering with Ruport and want to shake down me or Mike, this is also a chance for that.

From what I’ve seen so far, these regional Ruby conferences are always a lot of fun, especially because each one takes on its own unique flavor. If you want to go to this one, you should probably register soon because the event takes place on Friday, September 28, which is right around the corner.

Hope to see you there!

Gregory Brown

These days, it seems I hardly have the time for doing fun random hacks. So here I’ve started one, and if anyone finds it interesting, please take it from here and let me know how it turns out.

Loosely based off of AIML, kind of, but not really:

class Conversation

  def initialize(person)
    @person = person
    @response_id = 0
  end  

  attr_reader :response_id

  def say(msg)
    print "#{@person}: "
    @response_id = Response[@response_id].respond_to(msg)
  end 

  class Response

    def self.responses
       @responses ||= {}
    end

    def self.[](id)
      responses[id]
    end  

    def initialize(id)
      @id = id
      self.class.responses[id] = self
      @matchers = []
      @messages = []
    end               

    attr_reader :id,:matchers 

    def when(pattern,id)
      @matchers << [pattern,id]
    end     

    def inherits(arr)
      arr.each do |id|
        @matchers += Response[id].matchers
      end
    end

    def might_say(msg,weight=1)
      weight.times do
        @messages << msg
      end
    end        

    def talk
      puts @messages.sort_by { rand }.pop
    end

    def respond_to(msg)
      @matchers.each do |pattern,id|
        if msg =~ pattern
          Response[id].talk
          return id
        end
      end
      return @id
    end

  end     

end           

def response(id)
  r = Conversation::Response[id] || Conversation::Response.new(id)
  yield(r)
end

I’m looking for someone to take over PDF::Writer, color-tools, and Transaction::Simple. I do not have time to maintain these anymore. I should have done this months ago, but pride of ownership and a belief that more free time would be just around the corner got in the way.

You can read more details on my original blog posting at my personal blog.

Anyone interested? Anyone know anyone interested?

Gregory Brown

I think most Rubyists have picked up a good trick or two from Jim Weirich. Though it’s only a tiny part of his latest article (Using Flexmock to Test Computational Fluid Dynamics Code), I got excited to see his ‘Existence Test’ in his code:

  def test_initial_conditions
    q = F3DQueue.new
    assert_not_nil q
  end

Looks pretty simple, eh? You might be quick to say that this doesn’t do anything. However, it is actually a pretty clever practice. This test makes sure the tests themselves are working as expected. I was already in the habit of starting with a failure, usually something like:

  def test_doomed
    flunk
  end

The purpose of the above is simply to make sure your tests are picked up within your suite, and aren’t being overlooked by your Rakefile, autotest, or whatever runner you’re using. But the existence test actually goes a little farther. Because you’re initializing an object, you’re making sure that the files you need to be loading are present, that you can build your objects, *and* that your tests are hooked up.

After you’ve got a couple tests passing, you can remove this sanity check or morph it into a setup(), whatever makes sense.

Many people think this is a little paranoid, and most of the time, it is. Still, all it takes is one bad experience coding under falsely passing tests, and you’ll be converted in no time. :)

Gregory Brown

This package is the most simple way to equip your Macintosh Apple OSX System with Ruby - similar to the Windows Ruby One-Click Installer. It replaces the broken Readline library, updates to a current version of SQLite3 and prepares your OSX for Rails, which needs at least Ruby 1.8.4 to run. The current Ruby Version is 1.8.6 (1.8.5 is recommended for Rails) and Rubygems 0.9.4.

This package’s intention is to remain small while being a Universal Binary that serves everything to deploy Ruby Applications on OSX Machines - Cheetah, Puma, Jaguar, Panther, Tiger or Leopard. You don’t need to compile anything and you don’t need Apple’s Developer Tools (xcode) installed.

Some people use fink or other ports software, others (myself included) take the time to read through the HiveLogic post and do everything from scratch.

Now there’s another option, and if it lives up to its claims, it should be A Good Thing.

Gregory Brown

Well, our first ever spotlighted project has been selected. For June, it’s Sequel, the Concise ORM for Ruby.

Development on this project has been like wildfire for the last couple months, with releases every few weeks. Support is available for PostgresSQL, MySQL, SQLite3, and ODBC. There is also a wrapper for RubyDBI, which means that you can hook into pretty much any mainstream database if needed.

Because code often speaks louder than words, we’ll take a look at Sharon’s proposal which won the June spotlight.

From Nick Sutterer, A Computer Science Undergraduate at Albert-Ludwigs University (Freiburg, Germany)

When writing an article about Apotomo I had to make a decision: either introduce it as a simple widget plugin for rails or - as the name Apotomo (”all power to the model”) implies - end up in monologues about model-driven component-oriented enterprize concepts. Today I will simply introduce Apotomo as a widget library for rails.

Gregory Brown

Hey folks, I’ve picked a winner for June’s Ruby project spotlight and will have a post out within the next few days about it, but I’d like to remind folks that this is an ongoing project.

What that means is that I’m now accepting July submissions. Every submission we got for June was excellent, and if you were not selected, you can always resubmit for a later month. Here’s a recap of the rules, but see the original post for details.

  • Project must be fresh / actively developed
  • Project must be released before the time I post
  • Proposal should consist of nothing more than a code example and a link to your project page, no additional commentary needed
  • Project can’t be Rails-centric
  • You must be a developer on the project
  • My project choices will be entirely subjective and unjustified. :)

Please email me if you’ve got a cool project to submit!

Gregory Brown

To answer a question on RubyTalk the other day, I had to reference Mauricio Fernandez’s nicely compiled list of Changes in Ruby 1.9. While I was there I took another walk through the whole thing.

There are of course some features I *don’t* like.

a = ->(b,c){ b + c }
 a.call(1,2) # => 3

But there are quite a few that I do, and here I’ve listed ten I think will totally rock. I use Mauricio’s examples, so all credit goes to him. Also, this article is from February, so if you find any features below that have changed, shout and I’ll update.

Jim Alateras

Nice introductory tutorial on Rake from the guys @ Rails Envy, which provides a brief history, introduces concepts such as tasks and namespaces and talks about its role within Rails.

Curt Hibbs

It really makes me happy to see the increasing international interest in Rails and in Ruby. As I reported earlier, the official Ruby site is available in many languages (currently English, French, Japanese, Korean, Polish and Spanish), with more in the works. My original Rolling with Ruby on Rails was translated into Japanese, French, and Spanish. And now Bill Walton’s updated version of Rolling with Ruby on Rails has been translate to Brazilian Portuguese thanks to Gabriel Bogéa Perez!

Of course there is much more. If you know of Ruby and Rails resources in other native languages, please post the links in a comment and tell the rest of us about it!

Consider this fact: Multi-core CPUs are not only the future, they’re the only way CPUs can continue to grow at their current pace. It’s also a hotly debated subject in the software world. Multi-threaded programming is different and not seen as often as procedural programming, and therefore it’s not yet as well understood. So the question is, how can programming languages (and Ruby in particular) make it easier to harness these systems?

As Ruby struggles to graduate from its current implementation into something more powerful, we’ve already seen several projects attempt to update Ruby to help developers cope. Those who’ve been working with Ruby for awhile may remember YARV, which promises to provide more threading support. JRuby offers all the power of Java’s threads to Ruby, if it can harness it. And Evan Phoenix’s small but rapidly growing project Rubinius is attempting to be the next big contender.

No matter what implementation becomes the next de-facto Ruby platform, one thing is clear: People are interested in taking advantage of their newer, more powerful multi-core systems (as the recent surge in interest in Erlang in recent RailsConf and RubyConfs has shown). As Ruby becomes increasingly part of solutions that deal in high volumes of data processing, this demand can only increase.

That’s why it’s so very surprising to see David Heinemeier Hansson dismiss the whole notion out of hand regarding Rails. His argument seems to be that Rails already scales to multiple cores in the same way it scales to multiple machines, via UNIX process distribution. After all, isn’t this the very crux of “Share Nothing?”

We’ve got yet another project announcement to share, as Google’s Summer of Code begins to pick up steam. The following announcement is from Andreas Launila about his project Gecode/R. Andreas is pursuing a masters in Computer Science at KTH (The Royal Institute of Technology - Sweden).

Advertisement