Search code examples
activerecordliftbefore-savelift-mapper

How to apply transformations/filters on Lift Record Field before writing/reading its value


I'm using Lift Record persistence and I want to apply some transformations on a Field whenever I set or get its value. For instance, for StringField I want to set it to lower case automatically in Record object.

object someField extends StringField(this, 64) {
   ...
   // how do I apply transformations here?
   ...
}

In Lift Mapper there is a method setFilter which does exactly that, but I can't find its equivalent in Record. In Mapper it looks like this:

object someField extends MappedString(this, 64) {
   ...
   override def setFilter = trim _ :: toUpper _ :: super.setFilter
   ...
}

Couple options I'm considering are:

  • override set method, but there are many of them, I'm afraid to incompletely override subset of required methods, so I can't envision consequences. :)
  • using lifecycle callbacks - seems like overkill.

Any help is appreciated. Thanks ;)


Solution

  • Credit goes to @jcern for pointing this out:

    Record has method def setFilter: List[(ValueType) ⇒ ValueType] which is very similar to def setFilter: List[(FieldType) ⇒ FieldType].

    It is used the same way, i.e. filter will be applied when setting or querying values. Here is a quick example:

    class Tag extends MongoRecord[Tag] with ObjectIdPk[Tag] {
      ...
      object name extends StringField(this, 32) {
        override def setFilter = trim _ :: toLower _ :: super.setFilter
      }
      ...
    }
    
    Tag.createRecord.name("UPPER")                
    // lowercases tag name:
    //res1: Tag = class Tag={name=upper, _id=521bb306e4b04eacd74dd217}