Lift Web 框架 DRY 调度

发布于 2024-10-13 22:08:25 字数 681 浏览 5 评论 0原文

我有一个 Image 类:

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)
        }
    }
}

正如您所看到的,这是非 DRY 方法,因为您必须定义 URL (/gallery/image) 两次。

可以使其干燥吗?你能从 LiftRules 或其他东西获得路径吗?

提前致谢, 埃塔姆。

I have an Image class:

class Image extends LongKeyedMapper[Image] with IdPK with Logger {

which overrides toHtml method:

override def toHtml =
  <img src={"/gallery/image/%s/%s/%s/%s" format (slug.is, "fit", 100, 100)} />

and it works beacause of this:

def dispatch = {
    LiftRules.dispatch.append {
        case Req("gallery" :: "image" :: slug :: method :: width :: height :: Nil, _, _) => {
            () => Image.stream(slug, method, width, height)
        }
    }
}

As you can see this is not DRY approach, since you have to define the URL (/gallery/image) twice.

Is it possible to make it DRY? Can you get the path from LiftRules or something?

Thanks in advance,
Etam.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

苍暮颜 2024-10-20 22:08:25

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 :: _), _, _) => // ...

请参阅消息线程以获取更多建议。

This was answered by David Pollak on the lift list:

https://groups.google.com/d/topic/liftweb/VG0uOut9hb4/discussion

In short, you:

encapsulate the things in common (in this case, the path) in an object:

object ImageGallery {
  val path = "gallery" :: "image" :: Nil
  val pathLen = path.length
  def prefix = path.mkString("/", "/", "/")
}

create a custom unapply method that allows you to use the object in the pattern match in your dispatch method.

object ImageGallery {
  // ...
  def unapply(in: List[String]): Option[List[String]] = 
    Some(in.drop(pathLen)).filter(ignore => in.startsWith(path))
}

Your code is now:

<img src={ImageGallery.prefix+"%s/%s" ...}>

...and:

case Req(ImageGallery(slug :: method :: width :: height :: _), _, _) => // ...

See the message thread for more suggestions.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文