home

Easily Valgrind & GDB your Ruby C Extensions

Jun 8

When developing Nokogiri, the most valuable tool I use to track down memory-related errors is Valgrind. It rocks! Aaron and I run the entire Nokogiri test suite under Valgrind before releasing any version.

I could wax poetic about Valgrind all day, but for now I'll keep it brief and just say: if you write C code and you're not familiar with Valgrind, get familiar with it. It will save you countless hours of tracking down heisenbugs and memory leaks some day.

In any case, I've been meaning to package up my utility scripts and tools for quite a while. But they're so small, and it's so hard to make them work for every project ... it's looking pretty likely that'll never happen, so blogging about them is probably the best thing for everyone.

Basics

Let's get to it. Here's how to run a ruby process under valgrind:

      # hello-world.rb
require 'rubygems'
puts 'hello world'

# run from cmdline
valgrind ruby hello-world.rb

    

Oooh! But that's not actually what you want. The Matz Ruby Interpreter does a lot of funky things in the name of speed, like using uninitialized variables and reading past the ends of malloced blocks that aren't on an 8-byte boundary. As a result, something as simple as require 'rubygems' will give you 3800 lines of error messages (see this gist for full output).

Let's try this:

      valgrind --partial-loads-ok=yes --undef-value-errors=no ruby hello-world.rb

==15535== Memcheck, a memory error detector.
==15535== Copyright (C) 2002-2007, and GNU GPL'd, by Julian Seward et al.
==15535== Using LibVEX rev 1804, a library for dynamic binary translation.
==15535== Copyright (C) 2004-2007, and GNU GPL'd, by OpenWorks LLP.
==15535== Using valgrind-3.3.0-Debian, a dynamic binary instrumentation framework.
==15535== Copyright (C) 2000-2007, and GNU GPL'd, by Julian Seward et al.
==15535== For more details, rerun with: -v
==15535== 
hello world
==15535== 
==15535== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 0 from 0)
==15535== malloc/free: in use at exit: 10,403,440 bytes in 138,986 blocks.
==15535== malloc/free: 420,496 allocs, 281,510 frees, 155,680,688 bytes allocated.
==15535== For counts of detected errors, rerun with: -v
==15535== searching for pointers to 138,986 not-freed blocks.
==15535== checked 10,654,020 bytes.
==15535== 
==15535== LEAK SUMMARY:
==15535==    definitely lost: 21,280 bytes in 1,330 blocks.
==15535==      possibly lost: 27,368 bytes in 1,840 blocks.
==15535==    still reachable: 10,354,792 bytes in 135,816 blocks.
==15535==         suppressed: 0 bytes in 0 blocks.
==15535== Rerun with --leak-check=full to see details of leaked memory.

    

Ahhh, much better. We don't see any spurious errors.

Without going too far off-topic, I'd should just mention that those "leaks" aren't really leaks, they're characteristic of how the Ruby interpreter manages its internal memory. (You can see this by running this example with --leak-check=full.)

Rakified!

Here's an easy way to run Valgrind on your gem's existing test suite. This rake task assumes you've got Hoe 1.12.1 or higher.

      namespace :test do
  # partial-loads-ok and undef-value-errors necessary to ignore
  # spurious (and eminently ignorable) warnings from the ruby
  # interpreter
  VALGRIND_BASIC_OPTS = "--num-callers=50 --error-limit=no \
                         --partial-loads-ok=yes --undef-value-errors=no"

  desc "run test suite under valgrind with basic ruby options"
  task :valgrind => :compile do
    cmdline = "valgrind #{VALGRIND_BASIC_OPTS} ruby #{HOE.make_test_cmd}"
    puts cmdline
    system cmdline
  end
end

    

Those basic options will give you a decent-sized stack walkback on errors, will make sure you see every error, and will skip all the BS output mentioned above. You can read Valgrind's documentation for more information, and to tune the output.

If you're not testing a gem, or don't have Hoe installed, try this for Test::Unit suites:

      def test_suite_cmdline
  require 'find'
  files = []
  Find.find("test") do |f|
    files << f if File.basename(f) =~ /.*test.*\.rb$/
  end
  cmdline = "#{RUBY} -w -I.:lib:ext:test -rtest/unit \
               -e '%w[#{files.join(' ')}].each {|f| require f}'"
end

namespace :test do
  # partial-loads-ok and undef-value-errors necessary to ignore
  # spurious (and eminently ignorable) warnings from the ruby
  # interpreter
  VALGRIND_BASIC_OPTS = "--num-callers=50 --error-limit=no \
                         --partial-loads-ok=yes --undef-value-errors=no"

  desc "run test suite under valgrind with basic ruby options"
  task :valgrind => :compile do
    cmdline = "valgrind #{VALGRIND_BASIC_OPTS} #{test_suite_cmdline}"
    puts cmdline
    system cmdline
  end
end

    

Getting this to work for rspec suites is left as an exercise for the reader. :-\

A Note for OS X Users

Valgrind isn't just for Linux. You can make Valgrind work on your fancy-pants OS, too! Check out http://www.sealiesoftware.com/valgrind/ for details.

GDB FTW!

Another thing I find myself doing pretty often is running the test suite under the gdb debugger:

      gdb --args ruby -S rake test

    

or in your Rakefile:

      namespace :test do
  desc "run test suite under gdb"
  task :gdb => :compile do
    system "gdb --args ruby #{HOE.make_test_cmd}"
  end
end

    
‐ Posted via Flav-o-riffic

SOLID Object-Oriented Design (Sandi Metz)

May 30

Sandi Metz, a Dukie visiting from NC, will be talking about SOLID principles of software development:

  • Single Responsibility
  • Open Closed
  • Liskov Substitution
  • Interface Segregation
  • Dependency Inversion

All of Sandi's code is available here.

Change

Fact: your application is going to change. How will your application handle that change?

Robert Martin says your app can behave a couple of different ways:

  • Rigid: Making a change somewhere will break something somewhere else.
  • Fragile: You can't predict where that break will be.
  • Immobile: It's hard to change your code.
  • Viscous: It's easier to do the wrong thing than to fix things.

In the beginning, though, your app was perfect. "Dependencies are killing you!"

Design might save you.

The Design Stamina Hypothesis says that, after a certain point, you'll have done better if you had designed first.

"Skip design, if you want your app to fail."

To avoid dependencies, your design should be:

  • Loosely coupled
  • Highly cohesive
  • Easily composable
  • Context independent

Ignorable Rules

SOLID principles we can ignore in ruby:

  • Interface Segregation

    Really only a problem for statically-typed, compiled languages. Because we're in Ruby, we don't have this problem! Win!

    "Dynamic languages obey this rule in the most extreme way possible: duck typing."

  • Liskov Substitution

    When you design, don't break the contract of the superclass in the subclass.

Testing Interlude

Sandi draws her examples of applicatoin change from the source code at: http://skmetz.home.mindspring.com/img28.html.

Lesson #1: Resistance is a Resource.

  • Don't be attached to your first idea
  • Embrace the friction
  • Fix the problem

If testing seems hard, examine your design. Tests depend upon the design of the code. "TDD will punish you if you don't understand design."

During refactoring, ask yourself:

  1. Is it DRY?
  2. Does it have one responsibility?
  3. Does everything in it change at the same time?
  4. Does it depend on things that change less often than it does?

The answers should all be 'yes'.

Important Rules

Sandi references her code to demonstrate when and how to mock and use dependency injection to achieve Single Responsibility, in which a class both downloads and acts upon the downloaded data.

She urges developers to do the simplest possible refactoring when extracting responsibilities from a class.

"Refactor, not because you know the abstraction, but because you want to find it."

Sandi uses a very interesting example of building a Config class which behaves differently in different Rails environments. The first version had a lot of smell, and with a combination of hash parameters, YAML file, and metaprogamming, she demonstrates how to be open for extension, but closed for modification.

Sandi explains that paying attention to your classes' dependencies is important. If a relatively static class is dependent on a class that changes more often, that's a smell! Use dependency injection to avoid Dependency Inversion.

Summary

"TDD, BDD and DRY are all good, but they are not enough."

"Design because you expect your app to succeed, and the future to come."

Sandi recommends reading:

‐ Posted via Artifical Flavor

ROA with Waves (Dan Yoder)

May 30

Dan Yoder is the Director of Development at ATTi R&D, and will be talking about Waves, a Ruby architectural framework for developing RESTful apps.

A Brief History

Ruby web development came of age with MVC and Rails. Later, people who didn't need a full MVC invented Sinatra and other frameworkes. Which brings us to today, and ...

Waves Introduction

Waves can do simple apps in just a few lines of code. And by using "foundations", developers can build more advanced apps with MVC-like functionality. You can build your own foundation for whatever web framework you envision (there are several for MVC and REST).

Waves supports rack::cache and JRuby. It's Actually In Production(tm)!

Web as Services

As more rich browser apps use AJAX and COMET, server-side APIs are becoming more important. This is where REST shines.

"HTTP isn't MVC, but our frameworks think in MVC."

REST and ROA

"REST" shouldn't be applied to things that are "REST-influenced" (just ask Roy). Dan likes to use "Resource-Oriented" for these situations.

HTTP-based ROA uses the existing infrastructure, and has proven scalability. HTTP defines a protocol for a distributed hash table:

  • put(key, value)
  • get(key)
  • delete(key)

Q: "What about post?" A: "Post is for 'everything else'." Some things aren't clearly RESTful, and post is the catch-all for other operations.

What's in the hash? Resources, and keys are the URIs.

What's the point? Platform-neutral distributed objects! RDF can be used to describe discoverable resources.

ROA in action: rss/atom. It's one link to a resource describing your blog. "Boom! Podcasts for free." Dan describes this as the law of "unintended consequences," in a good way.

Edge caching is another big win for HTTP-based ROA.

How Does Waves Help?

Waves makes it easier to write resourceful applications like this today. New foundations will make it even easier going forward.

You can check out Waves at http://rubywaves.com, and on their Google Group.

‐ Posted via Artifical Flavor

Ruby Guide to *nix Plumbing (Eleanor McHugh)

May 30

Eleanor McHugh, a physicist by training, will be talking about how to make *nix systems work naturally within the Ruby environment.

The Unix Way

Eleanor actually hates Unix, but recognizes that it's a very effective operating system for getting things done. It's DRY: build little things, build them well, don't build them twice. There's a natural marriage between agile Ruby and the Unix philosophy.

Unix provides basic services which make it a very useful OS to "muck about with":

  • virtual memory
  • process management
  • hierarchical file system
  • user permissions
  • interprocess communication

Ruby provides some "really lovely" utilities:

  • Kernel.system
  • Kernel.spawn
  • IO.popen
  • Open3.popen3

However, if you're doing a lot of IO, you end up doing a lot of select()s and keeping a lot of file descriptors open.

System Calls with Ruby DL

DL, which Ruby delivers out of the box, is a way to wrap a C library with a Ruby call. This is a nice way to access the underlying kernel system calls without relying on the Ruby IO implementations.

This is superior to Ruby's syscall, in that you can actually get results back from the function call.

Using mmap allows you to do much faster memory reads, rather than do slower file reads.

Using kqueue/epoll/inotify allows you to build evented ruby (like EventMachine, but without EventMachine).

Using pipes allows you to build efficient IPC.

The drawback is that using DL means more verbose code, and more error prone code. (Pointer math FTL!) So, for things like sockets, use the Ruby API unless you specifically need kernel-level eventing.

Multicore

The lack of real thread support in Ruby can be addressed by using multiple processes, held together with IPC (sockets, pipes, memory mapped files). This is the traditional "Unix way" for handling multiple processes.

‐ Posted via Artifical Flavor

Where is Ruby Really Heading? (Gregory Brown)

May 30

Gregory Brown is the creator of Ruport and Prawn, and the author of the upcoming Ruby Best Practices. He'll be talking about the various-and-sundry Ruby implementations.

Moving to 1.9

On Ruby 1.8, strings are sequences of bytes. On Ruby 1.9, strings are proper characters (not bytes!). Even if your app only speaks "American", you still need to be aware of this to handle data properly. Plus, some of the new syntax in 1.9 is not backwards compatible with 1.8.

Recommended steps for upgrading from 1.8 to 1.9:

  1. make sure you have good test coverage!
  2. make sure your test are checking the output (some end-result validation)
  3. run on 1.9
  4. hammer on your code until the tests pass
  5. decide whether to continue to support 1.8

Prawn only officially supports 1.8.6 and 1.9.1 to make life easier, but if support more versions is necessary for your project, check out ZenTest's multiruby features.

Greg recommends using conditional-execution blocks to make version-dependent code look nicer:

      if RUBY_VERSION < "1.9"
 def ruby18
   yield
 end
else
 def ruby18
 end
end

    

Greg opines that moving to Ruby 1.9 is not a magic bullet, but has lots of advantages, so try it out!

Ruby 1.8.7

Ruby 1.8.6 is a workhorse (insert image of beat-up pickup truck). Ruby 1.9 is a Lamborghini (we think). "What the hell is 1.8.7?"

Answer: 1.8.7's patch set is largely 1.9 backports. It's a platypus!

However, this doesn't mean that code written for 1.9 will magically work on 1.8.7. Or that code written for 1.8.7 will work on 1.8.6.

What should authors be doing? Should we release for 1.8.6 or 1.8.7? Greg recommends releasing for 1.9, especially if you're writing a Ruby book (wink wink).

Peanut Gallery

Eric Hodel (maintainer of Rubygems), is planning on dropping 1.8.6 support within the next year, but continuing support for 1.8.7 and 1.9.

Writing Extensions

FFI (Foreign Function Interface) is supported "all over the place", and is an alternative to writing a C extension. FFI works across implementations (JRuby, Rubinius, and MRI).

On Windows, Greg proclaims that JRuby is the easiest way to wrap a C library. "WTF?"

Oversimplified Explanations of Ruby Variations

According to Greg. (Not all of the nuance may be captured here, since Greg was moving pretty quickly. Blame me, not him.)

  • 1.8.6 is ubiquitous, and may be slowing adoption of other, better interpreters.
  • YARV (1.9) is faster than Matz's implementation and is the only complete m17n implementation of Ruby.
  • Ruby Enterprise has a great installer!
  • JRuby is great and new, but requires C extensions to be rewritten
  • Rubinius is what created the RubySpec project and FFI, and is very innovative.
  • MacRuby is, um, Ruby for Macs.
‐ Posted via Artifical Flavor

Welcome to Goruco!

May 30

Good morning! Today Ben Woosley and I will be live-blogging what's going on during Goruco at Pace University.

You can check out some photos of the conference.

‐ Posted via Artifical Flavor

Parallelize Your RSpec Suite

May 8

We all have multi-core machine these days, but most rspec suites still run in one sequential stream. Let's parallelize it!

The big hurdle here is managing multiple test databases. When multiple specs are running simultaneously, they each need to have exclusive access to the database, so that one spec's setup doesn't clobber the records of another spec's setup. We could create and manage multiple test database within our RDBMS. But I'd prefer something a little more ... ephemeral, that won't hang around after we're done, or require any manual management.

Enter SQLite's in-memory database, which is a full SQLite instance, created entirely within the invoking process's own memory footprint.

(Note #1: the gist for this blog is at http://gist.github.com/108780)

(Note #2: The following strategy is relatively well-known, but I thought it might be useful for Pivots-and-friends to see exactly how one Pivotal project has used this tactic for a big speed win.)

Here's the relevant section of our config/database.yml:

      test-in-memory:
  adapter: sqlite3
  database: ':memory:'

    

Next, we need a way to indicate to the running rails process that it should use the in-memory database. We created an initializer file, config/intializers/in-memory-test.db:

      def in_memory_database?
  ENV["RAILS_ENV"] == "test" and 
    ENV["IN_MEMORY_DB"] and
    Rails::Configuration.new.database_configuration['test-in-memory']['database'] == ':memory:'
end

if in_memory_database?
  puts "connecting to in-memory database ..."
  ActiveRecord::Base.establish_connection(Rails::Configuration.new.database_configuration['test-in-memory'])
  puts "building in-memory database from db/schema.rb ..."
  load "#{Rails.root}/db/schema.rb" # use db agnostic schema by default
  #  ActiveRecord::Migrator.up('db/migrate') # use migrations
end

    

Note that in the above, we're initializing the in-memory database with db/schema.rb, so make sure that file is up-to-date. (Or, you could uncomment the line that runs your migrations.)

Let's give that a whirl:

      $ IN_MEMORY_DB=1 RAILS_ENV=test ./script/console 
Loading test environment (Rails 2.3.2)
connecting to in-memory database ...
building in-memory database from db/schema.rb ...
-- create_table("users", {:force=>true})
   -> 0.0065s
-- add_index("users", ["deleted_at"], {:name=>"index_users_on_deleted_at"})
   -> 0.0004s
-- add_index("users", ["id", "deleted_at"], {:name=>"index_users_on_id_and_deleted_at"})
   -> 0.0003s

...

>>

    

Super, we can see that the database is being initialized our of our schema.rb, and we get our console prompt. We're ready to roll!

But, running this:

      IN_MEMORY_DB=yes spec spec

    

will still only result in a single process, albeit one running off a database that's entirely in-memory. We want parallelization!

The final step is a script that will run your spec suite for you. You may need to edit this for your particular situation, but then again, maybe not.

      #  spec/suite.rb

require "spec/spec_helper"

if ENV['IN_MEMORY_DB']
  N_PROCESSES = [ENV['IN_MEMORY_DB'].to_i, 1].max
  specs = (Dir["spec/**/*_spec.rb"]).sort.in_groups_of(N_PROCESSES)
  processes = []

  interrupt_handler = lambda do
    STDERR.puts "caught keyboard interrupt, exiting gracefully ..."
    processes.each { |process| Process.kill "KILL", process }
    exit 1
  end

  Signal.trap 'SIGINT', interrupt_handler
  1.upto(N_PROCESSES) do |j|
    processes << Process.fork {
      specs.each do |array|
        if array[j-1]
          require array[j-1]
        end
      end
    }
  end
  1.upto(N_PROCESSES) { Process.wait }

else
  (Dir["spec/**/*_spec.rb"]).each do |file|
    require file
  end
end

    

Then, you simply run IN_MEMORY_DB=2 spec spec/suite.rb to run two parallel processes. Increase the number on larger machines for better results!

There's room for improvement here, notably in the naive method used to allocate the spec files to processes, but even as simple as this method is, our spec suite runs in about half the time it used to, on a dual-core machine.

‐ Posted via Artifical Flavor

Deliver Tracker Stories from Capistrano

Feb 15

The scene: Pivotal NYC
Jeff Dean walks up to Dan Podsedly, manager of Pivotal Tracker development.

Jeff: Hey Dan, you asked what features we wanted in Tracker. How about a way to automatically mark all my "Finished" stories as "Delivered", all at once?

Dan: (with a sly smile) Well, we have an API call for it ...

Thus was born my humble capistrano task which marks all your "Finished" stories as "Delivered". Hook it into your demo deploy task and save yourself some time.

As an added bonus, if you have Paul Dix's sax-machine gem installed (it's a SAX object parser that uses nokogiri, which I co-wrote with Aaron Patterson), you'll even get a brief summary report of the delivered stories in your cap output.

The code is below (you'll need to generate a Tracker API key). Now go deliver some stories!

      #
#  To use this task, simply set the following variables:
#
#    set :pivotal_tracker_project_id, PROJECT_ID
#    set :pivotal_tracker_token, TOKEN
#
#  Then, inside the task for your demo platform, add
#
#    task :demo do
#      ...
#      after :deploy, 'pivotal_tracker:deliver_stories'
#    end
#
namespace :pivotal_tracker do
  desc "deliver your project's 'finished' stories"
  task :deliver_stories do
    require 'rubygems'
    require 'activeresource'

    class Story < ActiveResource::Base
      self.site = "http://www.pivotaltracker.com/services/v2/projects/:project_id"
    end

    Story.headers['X-TrackerToken'] = pivotal_tracker_token
    puts "* delivering tracker stories ..."
    response = Story.put(:deliver_all_finished, :project_id => pivotal_tracker_project_id)

    begin
      require 'sax-machine'
      class Story
        include SAXMachine
        element :name
        element :story_type
        element :estimate
        element :description
      end
      class Stories
        include SAXMachine
        elements :story, :as => :stories, :class => Story
      end
      doc = Stories.parse(response.body)
      puts "* delivered #{doc.stories.length} stories"
      doc.stories.each do |story|
        puts "  - #{story.story_type}: #{story.name} (#{story.estimate} points)"
      end
    rescue LoadError => e
      puts "* stories delivered."
    end
  end
end

    
‐ Posted via Artifical Flavor

Nokogiri, Your New Swiss Army Knife

Nov 17

Prologue

Today I'd like to talk about the use of regular expressions to parse and modify HTML. Or rather, the misuse.

I'm going to try to convince you that it's a very bad idea to use regexes for HTML. And I'm going to introduce you to Nokogiri, my new best friend and life companion, who can do this job way better, and nearly as fast.

For those of you who just want the meat without all the starch:

  1. You don't parse Ruby or YAML with regular expressions, so don't do it with HTML, either.
  2. If you know how to use Hpricot, you know how to use Nokogiri.
  3. Nokogiri can parse and modify HTML more robustly than regexes, with less penalty than formatting Markdown or Textile.
  4. Nokogiri is 4 to 10 times faster than Hpricot performing the typical HTML-munging operations benchmarked.

The Scene

On one of the open-source projects I contribute to (names will be withheld for the protection of the innocent, this isn't Daily WTF), I came across the following code:

      def spanify_links(text)
  text.gsub(/<a\s+(.*)>(.*)<\/a>/i, '<a \1><span>\2</span></a>')
end

    

In case it's not clear, the goal of this method is to insert a <span> element inside the link, converting hyperlinks from

      <a href='http://foo.com/'> Foo! </a>

    

to

      <a href='http://foo.com/'> <span> Foo! </span> </a>

    

for CSS styling.

The Problem

Look, I love regexes as much as the next guy, but this regex is seriously busticated. If there is more than one <a> tag on a line, only the final one will be spanified. If the tag contains an embedded newline, nothing will be spanified. There are probably other unobvious bugs, too, and that means there's a code smell here.

Sure, the regex could be fixed to work in these cases. But does a trivial feature like this justify the time spent writing test cases and playing whack-a-mole with regex bugs? Code smell.

Let's look at it another way: If you were going to modify Ruby code programmatically, would you use regular expressions? I seriously doubt it. You'd use something like ParseTree, which understands all of Ruby's syntax and will correctly interpret everything in context, not just in isolation.

What about YAML? Would you modify YAML files with regular expressions? Hells no. You'd slurp it with YAML.parse(), modify the in-memory data structures, and then write it back out.

Why wouldn't you do the same with HTML, which has its own nontrivial (and DTD-dependent) syntax?

Regular expressions just aren't the right tool for this job. Jamie Zawinski said it best:

Some people, when confronted with a problem, think "I know, I'll use regular expressions." Now they have two problems.

Why, God? Why?

So, what drives otherwise intelligent people (myself included) to whip out regular expressions when it comes time to munge HTML?

My only guess is this: A lack of worthy XML/HTML libraries.

Whoa, whoa, put down the flamethrower and let me explain myself. By "worthy", I mean three things:

  • fast, high-performance, suitable for use in a web server
  • nice API, easy for a developer to learn and use
  • will successfully parse broken HTML commonly found on the intarwebs

libxml2 and libxml-ruby have been around for ages, and they're incredibly fast. But have you seen the API? It's totally sadistic, and as a result it's inappropriate and not easily usable in simple cases like the one described above.

Now, Hpricot is pure genius. It's pretty fast, and the API is absolutely delightful to work with. It supports CSS as well as XPath queries. I've even used it (with feed-normalizer) in a Rails application, and it performed reasonably well. But it's still much slower than regexes. Here's a (totally unfair) sample benchmark comparing Hpricot to a comparable (though buggy) regular expression (see below for a link to the benchmark gist):

      For an html snippet 2374 bytes long ...
                          user     system      total        real
regex * 1000          0.160000   0.010000   0.170000 (  0.182207)
hpricot * 1000        5.740000   0.650000   6.390000 (  6.401207)

it took an average of 0.0064 seconds for Hpricot to parse and operate on an HTML snippet 2374 bytes long

For an html snippet 97517 bytes long ...
                          user     system      total        real
regex * 10            0.100000   0.020000   0.120000 (  0.122117)
hpricot * 10          3.190000   0.300000   3.490000 (  3.502819)

it took an average of 0.3503 seconds for Hpricot to parse and operate on an HTML snippet 97517 bytes long

    

So, historically, I haven't used Hpricot everywhere I could have, and that's because I was overly-cautious about performance.

Get On With It, Already

Oooooh, if only there was a library with libxml2's speed and Hpricot's API. Then maybe people wouldn't keep trying to use regular expressions where an HTML parser is needed.

Oh wait, there is. Everyone, meet Nokogiri.

Check out the full benchmark, comparing the same operation (spanifying links and removing possibly-unsafe tags) across regular expressions, Hpricot and Nokogiri:

      For an html snippet 2374 bytes long ...
                          user     system      total        real
regex * 1000          0.160000   0.010000   0.170000 (  0.182207)
nokogiri * 1000       1.440000   0.060000   1.500000 (  1.537546)
hpricot * 1000        5.740000   0.650000   6.390000 (  6.401207)

it took an average of 0.0015 seconds for Nokogiri to parse and operate on an HTML snippet 2374 bytes long
it took an average of 0.0064 seconds for Hpricot to parse and operate on an HTML snippet 2374 bytes long

For an html snippet 97517 bytes long ...
                          user     system      total        real
regex * 10            0.100000   0.020000   0.120000 (  0.122117)
nokogiri * 10         0.310000   0.020000   0.330000 (  0.322290)
hpricot * 10          3.190000   0.300000   3.490000 (  3.502819)

it took an average of 0.0322 seconds for Nokogiri to parse and operate on an HTML snippet 97517 bytes long
it took an average of 0.3503 seconds for Hpricot to parse and operate on an HTML snippet 97517 bytes long

    

Wow! Nokogiri parsed and modified blog-sized HTML snippets in under 2 milliseconds! This performance, though still significantly slower than regular expressions, is still fast enough for me to consider using it in a web application server.

Hell, that's as fast (faster, actually) than BlueCloth or RedCloth can render Markdown or Textile of similar length. If you can justify using those in your web application, you can certainly afford the overhead of Nokogiri.

And as for usability, let's compare the regular expressions to the Nokogiri operations:

      html.gsub(/<a\s+(.*)>(.*)<\/a>/i, '<a \1><span>\2</span></a>') # broken regex
html.gsub(/<(script|noscript|object|embed|style|frameset|frame|iframe)[>\s\S]*<\/\1>/, '')

doc.search("a/text()").wrap("<span></span>")
doc.search("script","noscript","object","embed","style","frameset","frame","iframe").unlink

    

The Nokogiri version is much clearer. More maintainable, more robust and, for me, just fast enough to start jamming into all kinds of places.

Where Else Can I Use Nokogiri?

You can use Nokogiri anywhere you read, write or modify HTML or XML. It's your new swiss army knife.

What about your test cases? Merb is using Nokogiri extensively in their controller tests, and they're reportedly much faster than before. And those Merb dudes are S-M-R-T.

Have you thought about using Nokogiri::Builder to generate XML, instead of the default Rails XML template builder? Boy, I have. Upcoming blog post, hopefully.

Let me know where else you've found Nokogiri useful! Or better yet, join the mailing list and tell the community!

‐ Posted via Flav-o-riffic

Nokogiri: World's Finest (XML/HTML) Saw

Oct 31

Yesterday was a big day, and I nearly missed it, since I spent nearly all of the sunlight hours at the wheel of a car. Nine hours sitting on your butt is no way to ... oh wait, that's actually how I spend every day. Just usually not in a rental Hyundai. Never mind, I digress.

It was a big day because Nokogiri was released. I've spent quite a bit of time over the last couple of months working with Aaron Patterson (of Mechanize fame) on this excellent library, and so I'm walking around, feeling satisfied.

"What's Nokogiri?" Good question, I'm glad I asked it.

Nokogiri is the best damn XML/HTML parsing library out there in Rubyland. What makes it so good? You can search by XPath. You can search by CSS. You can search by both XPath and CSS. Plus, it uses libxml2 as the parsing engine, so it's fast. But the best part is, it's got a dead-simple interface that we shamelessly lifted from Hpricot, everyone's favorite delightful parser.

I had big plans to do a series of posts with examples and benchmarks, but right now I'm in DST Hell and don't have the quality time to invest.

So, as I am wont to do, I'm punting. Thankfully, Aaron was his usual prolific self, and has kindly provided lots of documentation and examples:

Use it in good health! Carry on.

P.S. Please start following Aaron on Twitter. :)

‐ Posted via Flav-o-riffic
Powered by aintablog