Advanced Rails - Building Industrial-Strength Web Apps in Record Time

(Tuis.) #1

182 | Chapter 6: Performance


Choosing the Right Tool


A large part of software development consists of selecting the right tools for the job.
This encompasses not only languages but libraries, frameworks, source control,
databases, servers, and all of the other tools and materials that go into a completed
application.


Leveraging external programs


Sometimes the best way to solve a problem is not to have a problem at all. Chances
are, if you have a moderately complicated technical problem, someone else has
solved it. 37signals’ Basecamp takes this approach when resizing images—rather
than dealing with the hassle of installing RMagick, they just shell out to ImageMagick:*


def thumbnail(temp, target)
system(
"/usr/local/bin/convert #{escape(temp)} -resize 48x48! #{escape(target)}"
)
end

Part of the beauty of scripting languages is that they were designed out of necessity,
so they have ways to glue disparate parts together. In addition, most scripting lan-
guages have a rich set of community-developed libraries available. Though CPAN
(Perl’s collection of third-party libraries) is the undisputed champion in this arena,
Ruby has Rubyforge (http://rubyforge.org) and the Ruby Application Archive (http://
raa.ruby-lang.org/).


Writing inline C code


Writing Ruby extensions in C used to be hard. If you wanted to rewrite performance-
sensitive functions, there were many things besides the actual code that you had to
deal with. Not so anymore.


Ryan Davis has unleashed an incredible tool, RubyInline,†for integrating C with
Ruby. This tool allows you to embed C/C++ code as strings directly within an appli-
cation. The strings are then compiled into native code (only to be recompiled when
they change) and installed into your classes. The canonical example, the factorial
function, shows just how fast and clean this can be:


require 'rubygems'
require 'inline' # gem install RubyInline
require 'benchmark'

class Test
# Standard Ruby factorial function

*http://www.loudthinking.com/arc/000598.html
http://www.zenspider.com/ZSS/Products/RubyInline/Readme.html

Free download pdf