Easy And/Or in Ruby on Rails

2

This missing feature of rails has really bugged me, but it’s so useful.

If you have a list of words such as: apples, oranges, and bananas as an array:

>> list = ['apples','oranges','bananas']
=> ["apples", "oranges", "bananas"]

You’d like to be able to have a variable length list and still have it look correct in the view. So a smaller list:

>> list = ['oranges','bananas']
=> ["oranges", "bananas"]

Should look like: “oranges and bananas”.

>> list = ['apples','oranges','bananas']
=> ["apples", "oranges", "bananas"]
>> and_or_list 'and', list
=> "apples, oranges, and bananas"
>> list.pop
=> "bananas"
>> and_or_list 'and', list
=> "apples and oranges"
>> list.pop
=> "oranges"
>> and_or_list 'and', list
=> "apples"

The following block of code will do just that:

  def and_or_list( andor, list )
	list = list.dup
	comma = (list.size > 2 ? ',' : '')
	list2 = list.pop if list.size > 1
	s = list.join(', ')
	s << comma+' '+andor+' ' + list2 if list2
	s
  end

Vioa!

Instant and easy listing of various things, in English. Your users will never know it’s generated.

I’ve wrapped it up in a neat little plug-in for you. Just install it in your vendor/plugins directory. It will automatically be available in your views.

AndOrList Module

Comments

  1. Trevor Johns said 1 day later:

    Nice and useful. Now you need to write a method to replace this:

    puts (x.length == 1 ? 'foo' : 'foos')

    Sure, it’s a one-liner, but I still see developers forget to handle this all the time. Not to mention the trinary operator tends to promote very long lines of code.

  2. Christopher Wojno said 3 days later:

    @Trevor Johns

    See my next article for your mixin.

(leave url/email »)

   Comment Markup Help Preview comment