Openhood

Rack::Test warning on Ruby 1.9.x

Image by by Jeremy Thomas on unsplash

If you’ve tried to use Rack::Test on Ruby 1.9.x, which is the default when using capybara for exemple, you’ve probably been bugged by nasty warning like this one:

(out)~/.rvm/gems/ruby-1.9.2-head/gems/rack-1.2.1/lib/rack/utils.rb:16: warning: regexp match /.../n against to UTF-8 string

This problem comes when trying to send any UTF-8 character in params. It may even happen without you trying to send any now the rails does automatically add a snowman in all your forms (not a joke). One solution to silence these warnings is to add:

$VERBOSE=nil

somewhere in your initialization. Another solution is to patch rack itself.

I propose an even better solution, the great escape_utils gem. Not only does it removes the warning, escaping will also be faster, I mean like 45x faster!

It’s nearly too easy to be true, just add this to your Gemfile:

gem "escape_utils"

Then somewhere in your initialization (like in config/initializer in your using Rails):

module Rack
  module Utils
    def escape(s)
      EscapeUtils.escape_url(s)
    end
  end
end

Problem solved! Now that you’re at it, why not add these lines too:

require "escape_utils/html/rack"
require "escape_utils/html/haml"

If you’re using erb instead of haml, replace last line by:

require "escape_utils/html/erb"

Now all your html escaping will be faster too, this couldn’t be easier!

Copyright © 2024 Openhood SARL