为什么 JSON::Builder 不使用 `with obj yield` 修饰符?
Why JSON::Builder not using `with obj yield` modifier?
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
因为很多时候你想传递一个构建器给另一个方法,而with ... yield.
里面没有办法引用self
此外,JSON::Builder
的使用频率不高,所以偶尔多写几个字符也没什么大不了的。
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
因为很多时候你想传递一个构建器给另一个方法,而with ... yield.
self
此外,JSON::Builder
的使用频率不高,所以偶尔多写几个字符也没什么大不了的。