Search code examples
scalaurl-rewritinglift

scala & lift: rewriting URL using variable declared outside LiftRules.statelessRewrite.append


I'm looking for a solution for rewriting URLs in lift using a list declared outside the scope of LiftRules.statelessRewrite.append

LiftRules.statelessRewrite.append {  
    case RewriteRequest(ParsePath("abc" :: Nil, _ , _ , _ ), _ , _ ) =>  
        RewriteResponse("index" :: Nil)
}

I'd like to have the following code working the same as the one above:

val requestList = "abc" :: Nil

LiftRules.statelessRewrite.append {  
    case RewriteRequest(ParsePath(requestList, _ , _ , _ ), _ , _ ) =>
        RewriteResponse("index" :: Nil)
}

Could anyone write how to get such functionality with lift 2.0?

[edit]

Could you also suggest the best way to access this list's suffix as parameter. What I would like to get is similar to:

LiftRules.statelessRewrite.append {  
  case RewriteRequest(ParsePath(`requestList` ::: List(someId), _ , _ , _ ), _ , _ ) =>  
    RewriteResponse("index" :: Nil, Map("someId" -> someId))
}    

Solution

  • Any lowercased variable in a case statement will create a new variable with that name, therefore requestList is going to be shadowed. Try this:

    val requestList = "abc" :: Nil
    
    LiftRules.statelessRewrite.append {
      case RewriteRequest(ParsePath(list, _ , _ , _ ), _ , _ ) if list == requestList =>
        RewriteResponse("index" :: Nil)
    }
    

    Another approach would be to use backticks (Scala ref: ‘stable identifier patterns’):

    LiftRules.statelessRewrite.append {
      case RewriteRequest(ParsePath(`requestList`, _ , _ , _ ), _ , _ ) =>
        RewriteResponse("index" :: Nil)
    }    
    

    In your case, the second form would be the canonical one to choose, but in general the first form will be more powerful.

    As a third alternative, you could also define val RequestList = requestList and match against the uppercased version, though I would advise against this unless you have a good reason for creating a capitalised RequestList.