首页 > 解决方案 > 为什么 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

标签: crystal-lang

解决方案


因为很多情况下你想把一个builder传给另一个方法,而里面没有办法self引用with ... yield.

此外,JSON::Builder它不经常使用,因此不时多写几个字符并没有太大区别。


推荐阅读