我有一个图像类:
class Image extends LongKeyedMapper[Image] with IdPK with Logger {
覆盖 toHtml 方法:
override def toHtml =
<img src={"/gallery/image/%s/%s/%s/%s" format (slug.is, "fit", 100, 100)} />
它之所以起作用是因为:
def dispatch = {
LiftRules.dispatch.append {
case Req("gallery" :: "image" :: slug :: method :: width :: height :: Nil, _, _) => {
() => Image.stream(slug, method, width, height)
}
}
}
如您所见,这是不干的方法,因为您必须定义 URL (/gallery/image) 两次。
是否可以让它变干?你能从 LiftRules 或其他东西得到路径吗?
提前致谢, 艾特姆。
最佳答案
David Pollak 回答了这个问题在电梯列表上:
https://groups.google.com/d/topic/liftweb/VG0uOut9hb4/discussion
简而言之,您:
将共同的事物(在本例中为路径)封装在一个对象中:
object ImageGallery {
val path = "gallery" :: "image" :: Nil
val pathLen = path.length
def prefix = path.mkString("/", "/", "/")
}
创建一个自定义的 unapply 方法,允许您在调度方法中使用模式匹配中的对象。
object ImageGallery {
// ...
def unapply(in: List[String]): Option[List[String]] =
Some(in.drop(pathLen)).filter(ignore => in.startsWith(path))
}
您的代码现在是:
<img src={ImageGallery.prefix+"%s/%s" ...}>
...和:
case Req(ImageGallery(slug :: method :: width :: height :: _), _, _) => // ...
查看消息线程以获取更多建议。
关于scala - 提升 Web 框架 DRY 调度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4748539/