且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Play Framework 2.1中视图的相对时间

更新时间:2023-02-23 17:16:34

@Jack提出了一个很好的答案。

@Jack suggested a pretty good answer.

这是他的代码的一个版本可能很有用,因为它会在需要时启用一些组合(检查功能不是作曲,但可以轻松改变以构图并显示更详细的值。)

Here is a version of his code that might be useful because it'll enable some composition if needed (the check function is not composing but could be easily changed to compose and show a more detailed since value)

package object pimps {

  import java.util.Date
  import org.joda.time.DateTime;
  import org.joda.time.Period;

  def step(f:Period => Int)(fi:String):Period => Option[String] = {
    def g(i:Int = 1) = i + " " + fi + (if (i==1) "" else "s") + " ago"

    (p:Period) => {
      f(p) match {
        case 0 => None
        case 1 => Some(g())
        case x => Some(g(x))
      }
    }
  }
  val yearsStep = step(_.getYears)("year")
  val monthsStep = step(_.getMonths)("month")
  val daysStep = step(_.getDays)("day")
  val hoursStep = step(_.getHours)("hour")
  val minutesStep = step(_.getMinutes)("minute")
  val secondsStep = step(_.getSeconds)("second")
  val steps = Seq(yearsStep, monthsStep, daysStep, hoursStep, minutesStep, secondsStep)

  val check = 
    (p:Period) =>
      steps.collectFirst {
        case f if f(p).isDefined => f(p).get
      }

  implicit class PimpedDate(col: Date) {

    def since() = {
      val period: Period = new Period(new DateTime(col), DateTime.now);
      check(period)
    }
  }
}

正如你所看到的,现在我们停在第一个匹配级别,我们也重复getter(getYears如果匹配将被调用两次)。

As you can see, for now we stop at the first matching level, and also we repeat the getter (getYears if matching will be called twice).

尽管如此,另一件需要注意的是使用隐式类,它已经在Scala 2.10中引入以缓解拉皮条

Nevertheless, another thing to note is the usage of implicit class which has been introduced in Scala 2.10 to ease the pimping