为什么JSON :: Builder不使用`with obj yield`修饰符?

问题描述 投票:0回答:1

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
crystal-lang
1个回答
0
投票

因为在许多情况下,您想将构建器传递给另一种方法,并且无法在self中引用with ... yield.

此外,JSON::Builder的使用频率不高,因此不必不时再写几个字符没有太大的区别。

© www.soinside.com 2019 - 2024. All rights reserved.