Skip to content

Instantly share code, notes, and snippets.

@heralight
Created November 7, 2012 10:41
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 heralight/4030796 to your computer and use it in GitHub Desktop.
Save heralight/4030796 to your computer and use it in GitHub Desktop.
implementation case class instead of enumeration in lift Mongodb Record : SingleStringTypedField
/*
* Copyright 2012 Heirko
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package code.field
import net.liftweb._
import record._
import field._
import reflect.Manifest
import xml._
import common._
import Box.option2Box
import json._
import util._
import Helpers._
import http.js._
import http.{S, SHtml}
import S._
import JE._
trait CaseEnum {
def id : String
}
abstract class SingleStringTypedField[OwnerType <: Record[OwnerType], SingleStringType <: CaseEnum](rec: OwnerType) ( implicit mf: Manifest[SingleStringType])
extends Field[SingleStringType, OwnerType] with MandatoryTypedField[SingleStringType] with BaseSingleStringTypedField[SingleStringType] {
def owner = rec
def setFromAny(in: Any): Box[SingleStringType] = in match {
case seq: Seq[_] if !seq.isEmpty => setFromAny(seq.head)
case _ => genericSetFromAny(in)
}
}
trait BaseSingleStringTypedField[SingleStringType <: CaseEnum] extends TypedField[SingleStringType] {
def fromString(s : String) : SingleStringType
def setFromString(s: String): Box[SingleStringType] = s match {
case "" if optional_? => setBox(Empty)
case _ => setBox(Full(fromString(s)))
}
def toForm: Box[NodeSeq] = Empty
def defaultValue = null.asInstanceOf[MyType]
override def optional_? = true
def asJs = valueBox.map(v => Str(v.id)) openOr JsNull
def asJValue: JValue = valueBox.map(v => JString(v.id)) openOr (JNothing: JValue)
def setFromJValue(jvalue: JValue): Box[MyType] = jvalue match {
case JNothing|JNull if optional_? => setBox(Empty)
case JString(s) => setFromString(s)
case other => setBox(FieldHelpers.expectedA("JString", other))
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment