I want to rewrite urls in generic ways. For example I have a list of urls in a CSV file, read them them and want to rewrite the URL in Liftweb.
e.g. the file contains
buy-electronics/products/:id
cheap-phones/products/:id
and I want to rewrite those to
/products?id=[id from path]
I've only found examples with case matching in Liftweb. With case matching it would look something like:
case RewriteRequest(
ParsePath("buy-electronics" :: "products" :: id :: Nil), _, _, _), _, _) => {
RewriteResponse(
List("products"), Map("id" -> id)
)
}
but I have found nothing on how to add rewriting rules in a generic way. Any ideas beside generating Scala code?
You can use pattern matching guards to achieve this.
In a simplified example, assuming the first part of the path (buy-electronics, cheap-phones) is the only thing that actually changes (maybe that even does the trick in your case), you could add a guard that checks whether it is contained in the list you read from the CSV file.
// actually read from CSV
val prefixes = Seq("buy-electronics", "cheap-phones")
case RewriteRequest(ParsePath(prefix :: "products" :: id :: Nil), _, _, _), _, _)
if (prefixes contains prefix) =>
RewriteResponse(List("products"), Map("id" -> id))
If you need more complex structures to be possible, you can bind the whole path in a variable (... ParsePath(path), _, ...
) and check whether that value matches some of the lines in your list, again in the guard expression.