Archive for the ‘Ruby’ Category

Encode HTML with Ruby

Friday, July 24th, 2009

Writing documentation for Javascript and HTML means code samples. These code samples need escaping so that they can be displayed on the web page. Instead of doing it over the web, why not do it in Ruby?

Here are a couple of simple scripts that I did (encode method straight out of the h method in rails):

Completely custom routes

Thursday, October 30th, 2008

In a recent project for the New Zealand business community, we were required to have some really custom routes. An example of such routes would be geographical routes, e.g. /china, or /china/beijing.

We could try something like this: ':country', :controller => :locations, :action => :show,
  :country =>'|'))
map.region ':country/:region', :controller => :locations, :action  => :show,
  :country =>{|c| "^#{}" }.join('|'))

However we get this error “Regexp anchor characters are not allowed in routing requirements”. So we can’t use requirements. However, we can use route conditions instead. With inspiration from Jamis Buck’s route monkeypatch :

# /lib/routing_extensions.rb
module ThongKuah
module Routing

  module RouteExtensions
    def self.included(base)
      base.alias_method_chain :recognition_conditions, :path_regexp

    # allows recognition for paths only matching the given regexp (conditions[:path])
    # allows recognition for paths not matching the given regexp (conditions[:not_path])
    def recognition_conditions_with_path_regexp
      result = recognition_conditions_without_path_regexp
      result << "conditions[:path] =~ path" if conditions[:path]
      result << "(conditions[:not_path]=~path).nil?" if conditions[:not_path]


# /config.environment.rb
require 'route_extension'
ActionController::Routing::Route.send :include, ThongKuah::Routing::RouteExtensions

So now we can go : ':country', :controller => :locations, :action => :show,
  :conditions => {:path =>'|'))}
map.region ':country/:region', :controller => :locations, :action => :show,
  :conditions => {:path =>{|c| "^#{}" }.join('|')) }

Note we can have negative matches as well. I’m sure the Regular expressions gods can do a negative match use Regexp only, but hey.

We found this rails idiom to be quite useful as this allows us full customisation of routing, if we need it. We have used it successfully for Made from New Zealand, so you check it out on pages such as and

Pastie of the code here.

Rails 2.0.2 – test setup not being called

Monday, April 21st, 2008

The setup method for ActionController::TestCase is useful in some circumstances, e.g. having a user login in your tests.

def setup
login_as :quentin

However, when you run the tests, all your tests with login_required fails.

Basically, this is a bug in Rails 2.0.2 where setup is not called. This was fixed in revision 8442 (one revision after rails 2.0.2 was released). See

So, we would want that revision by using:

rake rails:freeze:edge REVISION=8442

NOTE: is down/domain expired so rake might fail. In the meantime, try svn export or some other way to get revision 8442 from another repository.

UPDATE: is back up (domain renewed)!


Friday, September 28th, 2007

C2 Wiki discusses how nil.to_s.empty? is available in rails and nil.blank? is provided for Ruby On Rails,

>> true

>> true

String s = null;
return s == null;
>> true

Let’s say we want to check that s is non-blank string. The danger is that s could be null. We will use random to seed s (Or just think of it as the invisible hand typing a form value). In ruby we can do:
s = rand < 0.5 ? “” : nil
>> true

And in java?
String s = Math.random() < 0.5? “” : null;
return !s.equals(“”); //Playing roulette
>> NullPointerException?!

if (s!=null) {
return !s.equals(“”);
} else {
return false;
>> true

Verbosity, or simplicity? I feel that in web development where checking for blanks occur on a frequent basis, ruby has the better syntax. Not just in length, but it fits with my mental context as well.

Useful Rails links

Friday, September 7th, 2007

Some useful links (besides the obligatory introductions and tutorials)

Some Rails blogs I have in my aggregator

Testing RJS with assert_select_rjs

Thursday, August 23rd, 2007

I am surprised to find little about testing RJS in rails, with the exception of ARTS. However, assert_select_rjs seems to be the replacement to ARTS. This is nice, as we have now one less plugin to worry about. (I am of the opinion that testing plugins should be integrated into core if it is used in more than one test)

I’ll show you one example.

Let’s say that we have scaffolded our controllers, and now have a RJS function that we want to call when we destroy a membership. We first create our test

def test_should_destroy_membership
old_count = Membership.count
delete :destroy, :id => 1
assert_equal old_count-1, Membership.count
assert_response :success
assert_select_rjs :replace_html, “membership-action”

I am just testing if replace_html was called on the ‘membership-action’ element, without regard to what content is replaced into. If you want to test the content being replaced, pass the value to be compared as the second parameter of assert_select_rjs. E.g.

[source:ruby] assert_select_rjs :replace_html, “membership-action”, “Some Content”[/source]

Test and watch it go red.

Now we create our RJS template to make the test go green. The content can be anything, since I did not test for equality of the content to be replaced.

[source:ruby]page.replace_html ‘membership-action’, :partial => ‘memberships/join_link'[/source]

Run the test and feel the green.

Looking under the hood of assert_select_rjs, it seems that it is taking a copy of @response.body, and then running a Regular Expression match with the test values. Something worth knowing.

It also checks for content-type=text/javascript, so make sure your @response is returning javascript, otherwise the test will fail in a non-obvious way. If you forgot to include format.js in the controller, the assertion error message will be displayed as

“No RJS statement that replaces or inserts HTML content”

Just remember to put format.js in your controller, and you should be alright.

Time Picker for Rails

Tuesday, August 21st, 2007

Having worked with Rails for the past few weeks, I have discovered that it is awesome fun. So, when I encountered the time_select method of the DateHelper classes, and found that it outputs two drop downs for a single time (hours and minutes, three if you include seconds), I was not too happy.

Therefore I made a plugin for a single select for time. Time Picker is a plugin that gives you a nice view helper function for picking times.

So to install :

script/plugin install svn://


svn propset svn:externals 'timepicker svn://' vendor/plugins

This plugin is still quite alpha, so please use it and feel free report any problems or suggestions to me.

Ruby min/max

Friday, November 10th, 2006

I wondered why Ruby seemed to be missing min() and max() functions, which of course are very useful.
Turns out you’re supposed to use Enumerable.min and Enumerable.max like so:

irb(main):020:0> [2, 1].min
=> 1

Prime numbers, Ruby-style

Thursday, October 12th, 2006

Uses the Sieve of Eratosthenes technique, and the intruiging inject() method.
This returns an array of all the primes between 2 and 1000 inclusive.

(2..1000).inject((2..1000).to_a) {|res, i|{|n|n==i||n%i!=0} }