Reputation: 15336
Crystal allows to use with
keyword to improve DSL.
But in its standard library it's not used for JSON::Builder, the example from docs looks like that:
JSON.build do |json|
json.object do
json.field "name", "foo"
end
end
While it could be written shorter as:
JSON.build do
object do
field "name", "foo"
end
end
So, why it's not implemented in such way? Are there any drawbacks of using with xxx yield
?
Possible implementation
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
Upvotes: 1
Views: 66
Reputation: 2926
Because in many cases you want to pass a builder to another method, and there's no way to refer to self
inside with ... yield.
Additionally, JSON::Builder
isn't used that frequently so it's not a big difference to have to write a few more characters now and then.
Upvotes: 2