Can Ruby on Rails reply_ return a string if the format is not supported?

Normal use is respond_tosimilar to

respond_to do |format|
  format.html
  format.xml { render :xml => @data }
end

you can make it so that when the format is not supported (for example, json or csv is not supported above), instead of not returning anything, return a text line that says: "Format is not supported" or, even better, it automatically reports "only html and xml are supported"? He may know that only html and xml are supported by existing strings format.htmland format.xml. (if possible)

+3
source share
1 answer

you can use format.all

respond_to do |format|
  format.html
  format.xml { render :xml => @data }
  format.all { render :text=>'the format is not supported' }
end

, .

- config/initializers/extend_responder.rb

module ActionController
  module MimeResponds
    class Responder

      def valid_formats
        @order.map(&:to_sym)
      end

    end
  end
end

:

respond_to do |format|
  format.html
  format.json { render :text=>'{}' }
  format.all { render :text=>"only #{(format.valid_formats - [:all]).to_sentence} are supported" }
end
+6

Source: https://habr.com/ru/post/1761980/


All Articles