Skip to content

Instantly share code, notes, and snippets.

@brianhsu
Created January 10, 2010 05:54
Show Gist options
  • Save brianhsu/273344 to your computer and use it in GitHub Desktop.
Save brianhsu/273344 to your computer and use it in GitHub Desktop.
/**
* A RESTful-like URL handling Loc
*
* If you have the following templates:
*
* * webapps/item/edit.html
* * webapps/item/view.html
*
* You want the following URL map to corresponding template with
* last path component as a S parameter.
*
* http://localhost/item/edit/1 to http://localhost/item/edit
* http://localhost/item/view/1 to http://localhost/item/view
*
* You could create a Menu with this Loc class in your Model object.
*
* <code>
* object Item extends Item with LongKeyedMetaMapper[Item]
* {
* // Other methods here...
*
* def menu () {
*
* // What methods do we have?
* val methods = List ("view", "edit")
*
* val parameterName = "itemID"
* val itemLoc = new RESTfulLoc("Item", List("item"), "Item",
* methods, parameterName)
*
* Menu (itemLoc)
* }
* }
* </code>
*
* Now add the menu to SiteMap in Boot.boot
*
* <code>
* class Boot {
* def boot () {
*
* val entries = Item.menu :: Nil
*
* LiftRules.setSiteMap(SiteMap(entries:_*))
* }
* }
* </code>
*
*
* Finally, You could access the parameter in your snippet with
* S.param("itemID")
*
*/
class RESTfulLoc (val name: String, val path: List[String],
val text: LinkText[Unit], val methods: List[String],
val parameterName: String,
val locParams: LocParam[Unit]*) extends Loc[Unit]
{
override val defaultValue = Full(())
override val params = locParams.toList
override val link: Link[Unit] = (List(path.first), true)
def this (name: String, path: List[String], text: LinkText[Unit],
methods: List[String], locParams: LocParam[Unit]*) =
{
this (name, path, text, methods, "id", locParams:_*)
}
private def isTarget (path: ParsePath) =
{
path.partPath -- this.path match {
case List (action, id) => {
(methods contains action) && id != "index"
}
case _ => false
}
}
override def rewrite = Full (NamedPF("RESTfulLoc")
{
case RewriteRequest (path, _, _) if isTarget(path) => {
val parameter = path.partPath.last
val action = path.partPath.init
val data = Map (parameterName -> parameter)
RewriteResponse(action, data) -> ()
}
})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment