It’s important to highlight the correlation between the format and template name. For a given MIME Type, Rack (and then Hanami) associate a format for it. XML is mapped from to :xml
, HTML is text/html
and becomes :html
for us.
Format MUST be the first extension of the template file name. Eg dashboard/index.html.*
.
% curl -H "Accept: application/json" http://localhost:2300/dashboard
{"foo":"bar"}
We’re still able to request HTML format.
% curl -H "Accept: text/html" http://localhost:2300/dashboard
In case we request an unsupported MIME Type, our application will raise an error.
View For Specific Format
We can inherit from our view and declare that our subclass only handles a specific format.
# apps/web/views/dashboard/json_index.rb
module Web
module Views
module Dashboard
class JsonIndex < Index
format :json
raw JSON.generate({foo: 'bar'})
end
end
end
end
JSON requests for /dashboard
, will be handled by our JsonIndex
.
With the example above we took advantage of custom rendering to not use the template and let our serializer to return JSON for us.