Skip to content

Instantly share code, notes, and snippets.

@tgpfeiffer
Created January 3, 2013 13:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tgpfeiffer/4443477 to your computer and use it in GitHub Desktop.
Save tgpfeiffer/4443477 to your computer and use it in GitHub Desktop.
Mapper inheritance
import scala.xml.Text
import scala.annotation.tailrec
import net.liftweb.mapper._
import net.liftweb.sitemap._
import net.liftweb.common._
import net.liftweb.http._
import net.liftweb.util.Helpers._
import net.liftweb.sitemap.Menu.ParamExtractor
import eu.vismath.web.lib._
/*
* This class inherits Translation and passes in its own type as a
* type parameter. It will have all fields that the translation class
* has, and it can add some new fields. There will be a table for this
* class, but not for the superclass, i.e. it is non-trivial to find
* "all other XyzTranslations" in the database.
*/
class FilmTranslation extends Translation[FilmTranslation, Film](Film)
with LongKeyedMapper[FilmTranslation] with IdPK
with ManyToMany {
override def getSingleton = FilmTranslation
object title extends MappedString(this, 100)
object subtitle extends MappedString(this, 256)
}
object FilmTranslation extends FilmTranslation with LongKeyedMetaMapper[FilmTranslation] with CRUDify[Long, FilmTranslation] {
override def dbIndexes = indexes ++ super.dbIndexes
}
import net.liftweb.mapper._
import net.liftweb.common._
import net.liftweb.http.S
/*
* This class is the base class for FilmTranslation, BookTranslation, ...
* It does *not* inherit LongKeyedMapper and there will *not* be a table
* for this class, but it will add common fields to all classes that
* inherit it.
* The "secret" is that we pass in the "Owner" class as a type parameter
* and then can say MappedString(this.asInstanceOf[Owner], 100).
*/
abstract class Translation[Owner<:LongKeyedMapper[Owner], T<:LongKeyedMapper[T]](_foreignMeta: => LongKeyedMetaMapper[T]) {
def getSingleton : LongKeyedMetaMapper[Owner]
object translates extends MappedLongForeignKey(this.asInstanceOf[Owner], _foreignMeta) {
override def validSelectValues =
Full(_foreignMeta.findAll.map(p => (p.primaryKeyField.is, p.toString)))
}
object locale extends MappedLocale(this.asInstanceOf[Owner])
object slug extends MappedString(this.asInstanceOf[Owner], 100)
// slug and translated object are unique per language
protected def indexes : List[BaseIndex[Owner]] =
UniqueIndex(List(IndexField(translates), IndexField(locale))) ::
UniqueIndex(List(IndexField(slug), IndexField(locale))) ::
Nil
// find translated objects from their slug
protected def finder(param : String) : Box[Owner] = {
getSingleton.find(By(slug, param),
By(locale, S.locale.getLanguage))
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment