|
5月23日 西安 OSC 源创会开始报名啦,存储、虚拟机、Docker 等干货分享
Form-binder v0.9.0 发布了。主要是改动了 `FormBinder.bind` 的方法签名。
这一改动会对普通用户的使用方式造成一些影响:
原来的应用代码是这样的
import com.github.tminglei.bind.simple._
val binder = expandJsonString("body", Some("json")) >-: FormBinder(messages)
val mappings = tmapping(
"id" -> long(),
"json" -> tmapping(
"email" -> required() >+: text(email()),
"price" -> (cleanPrefix("$") >-: float()),
"count" -> number().verifying(min(3), max(10))
).label("xx").verifying { case (label, (email, price, count), messages) =>
if (price * count > 1000) {
Seq("" -> s"$label: $price * $count = ${price * count}, too much")
} else Nil
}
)
val data = Map(
"id" -> "133",
"body" -> """{"email":"test@example.com", "price":"$137.5", "count":5}"""
)
binder.bind(mappings, data) { case (id, (email, price, count)) =>
//do something here ...
}
现在会变成这样
import com.github.tminglei.bind.simple._
val binder = expandJsonString("body", Some("json")) >-: FormBinder(messages)
val mappings = tmapping(
"id" -> long(),
"json" -> tmapping(
"email" -> required() >+: text(email()),
"price" -> (cleanPrefix("$") >-: float()),
"count" -> number().verifying(min(3), max(10))
).label("xx").verifying { case (label, (email, price, count), messages) =>
if (price * count > 1000) {
Seq("" -> s"$label: $price * $count = ${price * count}, too much")
} else Nil
}
)
val data = Map(
"id" -> "133",
"body" -> """{"email":"test@example.com", "price":"$137.5", "count":5}"""
)
binder.bind(mappings, data).fold(
errors => errors,
{ case (id, (email, price, count)) =>
//do something here ...
}
)
注:在 bind 以后的使用代码需要做些调整。
----------------------------------------------
原来的接口是可以处理 errors 的,通过 ErrProcessor,但新的接口无疑更灵活些;可以通过配置 ErrProcessor 统一做些预处理,真正绑定后在具体运行环境中再做最终处理。
另外,我正在把 form-binder 和 Scalatra 的集成文档添加进 Scalatra Guide,如果顺利,不久就可以在 Scalatra 官网的文档里见到它了。
form-binder 是一个容易使用和定制的微型数据绑定和校验框架。
它有如下特点:
- 非常轻量,总共才 700 多行代码(框架 + 内置扩展)
- 容易使用,使用过程没有冗余代码,所见及所得
- 高度可定制,你可以扩展几乎每一个执行点
- 容易扩展,每个扩展接口都只是一个 FunctionN 的别名
- 不可变性,让你可以安全的共享/(嵌套)复用 mapping定义对象
|
|
|