views:

32

answers:

1

I'm working on a Rails site that uses the Radiant CMS and am building stateful navigation as per the first method in this link.

I'm matching the URL on regular expressions to determine whether or not to show the active state of each navigation link. As an example, here are two sample navigation elements, one for the Radiant URL /communications/ and one for /communications/press_releases/:

    <r:if_url matches="/communications\/$/"><li class="bottom-border selected">Communications</li></r:if_url>
    <r:unless_url matches="/communications\/$/"><li class="bottom-border"><a href="/communications">Communications</a></li></r:unless_url>
    <r:if_url matches="/communications\/press_releases/"><li class="bottom-border selected">Press Releases</li></r:if_url>
    <r:unless_url matches="/communications\/press_releases/"><li class="bottom-border"><a href="/communications/press_releases">Press Releases</a></li></r:unless_url>

Everything's working fine for the Press Releases page--that is, when the URL is /communications/press_releases the Press Releases nav item gets the 'selected' class appropriately, and the Communications nav item is unselected. However, the Communications regular expression doesn't seem to be functioning correctly, as when the URL is /communications/ neither element has the 'selected' class (so the regex must be failing to match). However, I've tested

>> "/communications/".match(/communications\/$/)
=> #<MatchData:0x333a4>

in IRB, and as you can see, the regular expression seems to be working fine. What might be causing this?

TL;DR: "/communications/" matches /communications\/$/ in the Ruby shell but not in the context of the Radiant navigation. What's going on here?

+1  A: 

From Radiant's wiki, it looks like you don't need to add /s around your regexs or escape /s. Try:

<r:if_url matches="/communications/$"><li class="bottom-border selected">Communications</li></r:if_url>
<r:unless_url matches="/communications/$"><li class="bottom-border"><a href="/communications">Communications</a></li></r:unless_url>
<r:if_url matches="/communications/press_releases/"><li class="bottom-border selected">Press Releases</li></r:if_url>
<r:unless_url matches="/communications/press_releases/"><li class="bottom-border"><a href="/communications/press_releases">Press Releases</a></li></r:unless_url>

What is happening behind the scenes is that Radiant calls Regex.new on the string in matches, so the regex you were trying to match before was this one:

 Regexp.new '/communications\/$/'
# => /\/communications\/$\// 

which translates to 'slash communications slash end-of-line slash' which I really doubt is what you want.

Ruby Regexs are interesting in that there are symbols for both start(^) and end of line($) as well as start(\A) and end of string(\Z). That's why sometimes you will see people using \A and \Z in their regexes.

BaroqueBobcat
Spot on, sir! Thank you very much.
justinbach