Amber: respond_with json method doesn't work

Created on 25 Jun 2018  路  7Comments  路  Source: amberframework/amber

Description

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.

Steps to Reproduce

  1. Create an application and a controller where in a get request you respond with JSON using the method respond_with { json "{}" }.
  2. Try to compile/run the application with amber w.
  3. You'll be greeted with this error.

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.

Versions

Amber CLI (amberframework.org) - v0.8.0

Crystal 0.25.0 (2018-06-20)

LLVM: 5.0.1
Default target: x86_64-apple-macosx

Additional Information

According to our gitter chat -

@faustinoaq thinks that "new proc type in respond_with helpers just broke something"

bug Important investigate

Most helpful comment

@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?

All 7 comments

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.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

elorest picture elorest  路  6Comments

faustinoaq picture faustinoaq  路  5Comments

bigforcegun picture bigforcegun  路  3Comments

elorest picture elorest  路  7Comments

nicbet picture nicbet  路  7Comments