Skip to content
This repository has been archived by the owner on Dec 7, 2022. It is now read-only.

Params enhancements

m20o edited this page Jan 20, 2012 · 4 revisions

This extensions enrich both the Scalatra' params and multiParams by adding a getAs[T] method that returns an Option[T].

String => T conversions occurs by mean of TypeConversion[T] classes that can be, implicitly or explicitly, passed to getAs methods, as showed above:

import mm.scalatra.extension.Params._

  get("/basic") {

    // Trivial...
    val name: Option[String] = params.getAs[String]("name")

    // Slightly less trivial...
    val age = params.getAs[Int]("age")  // returns an Option[Int]

    // Date formats are handled differently
    val birthDate = params.getAs[Date]("birthdate" -> "MM/dd/yyyy") // Option[Date]

    //  The same holds for multiParams
    val codes = multiParams.getAs[Int]("codes") // returns an Option[Seq[Int]]
  }

  get("/custom") {
    // Custom types can be also handled  by defining an appropriate TypeConverter
    case class Foo(bar:Int)

    // A TypeConverter can be created as a class...
    class FooTypeConverter extends TypeConverter[Foo] {
      def convert(string: String) = try {
        Some(Foo(string.toInt))
      } catch {
        case _ => None
      }
    }
    
    // ...or from a function (String) =>T or (String) => Option[T]  through implicit conversions
    val fooConverter: TypeConverter[Foo] = (s:String) => Foo(s.toInt)

    // Custom TypeConverters can be passed explicitely...
    val foo = params.getAs[Foo]("foo")(fooConverter)

    // ...or implicitly
    implicit val fooconv = new FooTypeConverter
    val bar = params.getAs[Foo]("bar")
  }

See this gist for the complete example.

Clone this wiki locally