Monday, October 1, 2007

Camping: optional group in regular expression

Recently I finished a Camping application where I wanted to handle URIs with an optional part. Like so:
class Jar < R '/(.*)\.jar(\.sha1|\.md5)?' def get(jarname, hash) # does not work ... end end
Unfortunately this does not work. (Does this look familiar? See my next post!) In the end it turned out to be as simple as:
class Jar < R '/(.*)\.jar(\.sha1|\.md5)?' def get(jarname, hash = nil) ... end end
At RailsconfEurope Manfred taught me another trick:
n = 4 class DigitParty < R "/" + ("(\\d)?" * n) def get(*args) args.length # -> 4 args[0] # -> first digit or nil args[n - 1] # -> last digit or nil end end
This matches anything from 0 to n digits where a group is created for each digit. Using * in the parameter list will make method get work for any value of n. For URI's with less then n digits, the corresponding array elements are nil.

1 comment:

  1. Thank you for this it was really really really helpful! How incredibly generous of you to post this!

    Cheers,
    Candice

    ReplyDelete