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?

Stefan
  • 109,145
  • 14
  • 143
  • 218
Undistraction
  • 42,754
  • 56
  • 195
  • 331
  • 1
    try params[:format] http://stackoverflow.com/questions/1671111/methods-for-limiting-the-rails-render-format-to-html – gayavat Jun 22 '12 at 14:00

2 Answers2

90

The method to access the format is:

controller.request.format
Anil
  • 3,899
  • 1
  • 20
  • 28
20

in your controller you can do:

request.format
request.format.html?
request.format.js?
request.format.json?
# etc.
localhostdotdev
  • 1,795
  • 16
  • 21
  • I can't find any documentation on the available types or how they are built. Do you know where this is defined? – estani Aug 17 '20 at 12:24
  • 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: https://guides.rubyonrails.org/layouts_and_rendering.html – CWarrington Aug 05 '21 at 17:32