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
因为在许多情况下,您想将构建器传递给另一种方法,并且无法在self
中引用with ... yield.
此外,JSON::Builder
的使用频率不高,因此不必不时再写几个字符没有太大的区别。