Method: Hanami::API::Block::Context#json

Defined in:
lib/hanami/api/block/context.rb

#json(object, mime = "application/json") ⇒ Object

Sets a JSON response for the given object

Examples:

JSON serializable object

get "/user/:id" do
  user = UserRepository.new.find(params[:id])
  json(user)
end

JSON serializable object and custom MIME type

get "/user/:id" do
  user = UserRepository.new.find(params[:id])
  json(user, "application/vnd.api+json")
end

Parameters:

  • object (Object)

    a JSON serializable object

  • mime (String) (defaults to: "application/json")

    optional MIME type to set for the response

Since:

  • 0.1.0



125
126
127
128
129
130
131
132
133
# File 'lib/hanami/api/block/context.rb', line 125

def json(object, mime = "application/json")
  headers["Content-Type"] = mime
  case object
  in Enumerator => collection
    json_enum(collection)
  else
    JSON.generate(object)
  end
end