crystal-lang - 为什么 JSON::Builder 不使用 `with obj yield` 修饰符?
问题描述
Crystal 允许使用with
关键字来改进 DSL。
但在其标准库中,它不用于 JSON::Builder,文档中的示例如下所示:
JSON.build do |json|
json.object do
json.field "name", "foo"
end
end
虽然它可以写得更短:
JSON.build do
object do
field "name", "foo"
end
end
那么,为什么不以这种方式实施呢?使用有什么缺点with xxx yield
吗?
可能的实施
class JSON
def self.build
with JSON.new yield
end
def object
builder = JSONObject.new
with builder yield self
p builder.result
end
class JSONObject
getter :result
@result = Hash(String, String).new
def field(key : String, value : String)
@result[key] = value
end
end
end
解决方案
因为很多情况下你想把一个builder传给另一个方法,而里面没有办法self
引用with ... yield.
此外,JSON::Builder
它不经常使用,因此不时多写几个字符并没有太大区别。
推荐阅读
- terraform - 地形执行
- r - 如何让我的 R Shiny 应用程序停止获取变量的无效类型(列表)?
- google-cloud-automl - 如何在 Google Auto ML 自然语言实体提取中重命名实体提取标签?
- azure-cosmosdb - cli az cosmosdb 对容器数据的访问支持什么?
- sas - SAS Studio 大变量到变量
- azure - 尝试创建 Blob 容器时,无法将“System.Object []”转换为参数“StorageAccountKey”所需的类型“System.String”
- xaml - 在 UWP 中设置 ContentDialog 的宽度
- c - 是否可以在 C 中使用正则表达式条件?
[前面的正则表达式无效] - css - Flexbox:按比例缩放图像到动态父高度
- reactjs - Antd modal 对自定义钩子状态更改没有反应