Lanbo
Lanbo

Reputation: 15692

Create specialised fields in Lift's Record Framework

One of the nice advantages of Scala is the way you can be type safe, so that no undefined values will appear in the application. Mongo, however, is not type safe at all. So, I thought, a kind of conversion to and from Mongo is good, to make sure only the right values are saved (as strings). I have this type in my Scala:

sealed trait Tribe

object Tribe {
  def fromString(s:String) = s match {
    case "Earth Pony" => EarthPony
    case "Pegasus" => Pegasus
    case "Unicorn" => Unicorn
    case "Alicorn" => Alicorn
    case _ => throw new NoSuchElementException
  }
}

case object EarthPony extends Tribe {
  override def toString = "Earth Pony"
}

case object Pegasus extends Tribe {
  override def toString = "Pegasus"
}

case object Unicorn extends Tribe {
  override def toString = "Unicorn"
}

case object Alicorn extends Tribe {
  override def toString = "Alicorn"
}

Now I want to make a field TribeField which I can employ in a MongoRecord class to make sure this conversion is done when I read the Record, or save it.

Unfortunately, the documentation on Lift's Record seems sparse, and so far I have not found any helpful information on how to do this. Maybe someone here can give me some hints?

Upvotes: 1

Views: 182

Answers (1)

Dave Whittaker
Dave Whittaker

Reputation: 3102

I'm fairly sure that lift-record-mongodb uses the ability of lift-record Field instances to serialize/deserialize to and from JSON via Field.asJValue and Field.setFromJValue. To make a completely type safe Tribe Field, you'd want to create your own TypedField[Tribe] and implement those methods along with the other abstract methods that set and access your field. I'd recommend taking a look at StringField or one of the other concrete Field types for pointers on how to do that.

An easier alternative would be to extend StringField itself and add setTribe/asTribe methods.

If you need more info, particularly on Lift's Mongodb integration, I'd recommend you try the Lift Google Group. Tim Nelson who maintains that code is usually pretty quick to respond to questions.

Upvotes: 2

Related Questions