How to tell which format a controller has resolved to render
Asked Answered
A

2

55

In a rails controller action with the following code:

respond_to do |format|
  format.json{ render :json=>  {:status => 200, :response=>@some_resource} }
  format.html { redirect_to(some_resource_path)}
end

How can I log the format the controller will resolve i.e. 'HTML' or 'json'? format is of type Collector. Is there a way of getting a string denoting the format?

Algebraist answered 22/6, 2012 at 13:34 Comment(1)
try params[:format] #1671611Peroxy
U
90

The method to access the format is:

controller.request.format
Unformed answered 22/6, 2012 at 14:18 Comment(2)
Thanks Anil. So from the controller it is just request.format.Algebraist
Better to use request.format, because controller.request.format throws undefined local variable or method `controller'Jepson
O
21

in your controller you can do:

request.format
request.format.html?
request.format.js?
request.format.json?
# etc.
Oneiric answered 18/4, 2019 at 23:2 Comment(2)
I can't find any documentation on the available types or how they are built. Do you know where this is defined?Griceldagrid
Using the byebug gem in my controller, I was able to type formats in the debug session and I got this output: [:js, :html, :text, :css, :ics, :csv, :vcf, :vtt, :png, :jpeg, :gif, :bmp, :tiff, :svg, :mpeg, :mp3, :ogg, :m4a, :webm, :mp4, :otf, :ttf, :woff, :woff2, :xml, :rss, :atom, :yaml, :multipart_form, :url_encoded_form, :json, :pdf, :zip, :gzip] See this documentation: guides.rubyonrails.org/layouts_and_rendering.htmlDamning

© 2022 - 2024 — McMap. All rights reserved.