I was trying to send a JSON response from controller, and so I used respond_with method and json method in the block. Compiler threw an undefined method error which looked like this :-
in src/controllers/app_controller.cr:18: undefined method 'json'
respond_with { json "{}" }
This is actually the documented usage as well, so I am not sure what could have been different about my code.
respond_with { json "{}" }.amber w.Expected behavior: It should compile and return the string as a response.
Actual behavior: Doesn't compile.
Reproduces how often: Always when I've tried it.
Amber CLI (amberframework.org) - v0.8.0
Crystal 0.25.0 (2018-06-20)
LLVM: 5.0.1
Default target: x86_64-apple-macosx
According to our gitter chat -
@faustinoaq thinks that "new proc type in respond_with helpers just broke something"
This seems to be intentional as the "{}" is a string see https://github.com/amberframework/amber/blob/master/src/amber/controller/helpers/responders.cr#L38 you might want to pass an empty Hash or Array.
@eliasjpr I think we can use method overloading instead of union types.
Something like this:
def json(json : String)
# ...
end
def json(json : ProcType)
# ...
end
def json(json : Hash(Symbol | String, String))
# ...
end
WDYT?
My bad. I guess I can simply JSON.parse("{}") here.
This turned out to be a very verbose solution - json JSON.parse(json_host.data.as(String)).to_json (json_host is a model object with the field data).
Anything else gave an error. I guess def json doesn't accept a JSON object.
@shobhitic you must do JSON.parse("{}") and it should work see https://play.crystal-lang.org/#/r/4eh5
@eliasjpr Yes, I had done that, but it didn't compile without the .to_json method call.
Fix merged. closing.
Tested original question above and it works.
Most helpful comment
@eliasjpr I think we can use method overloading instead of union types.
Something like this:
WDYT?