DRY web-based lifting platform

I have an Image class:

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

which overrides the HTML method:

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

and this works because 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 approach is not DRY , since you must define the URL (/ gallery / image) twice.

Is it possible to do it DRY? Can you get a path from LiftRules or something else?

Thanks in advance, Etam.

+3
source share
1 answer

This was answered by David Pollack in the elevator:

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

In short, you:

encapsulate common things (in this case, the path) in the 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 a pattern match in the submit method.

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

Your code:

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

... and:

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

See the subject line for more details.

+4
source

Source: https://habr.com/ru/post/1786691/


All Articles