0

I have a rails application in which most of the actions respond to json.

Is there any "switch" I can turn off to prevent all the controllers from responding to json despite the respond_to method call, or I still have to disable it manually in every action (which seems very odd).

Tamer Shlash
  • 9,314
  • 5
  • 44
  • 82

2 Answers2

4

I have a proposal, though a bit hacky I'm afraid :)

class < ApplicationController
  before_filter :disable_json

  def disable_json
    if request.format =~ /json/
      //do something you like, redirect_to or reply with message
    end
  end

The before_filter will be fired before any specific controller's method.

The json header is usually "application/json"

For request, you can read more here: http://guides.rubyonrails.org/action_controller_overview.html#the-request-object

Billy Chan
  • 24,625
  • 4
  • 52
  • 68
  • Actually this is a very good solution, couldn't find any better one, thanks :) – Tamer Shlash May 14 '13 at 01:48
  • @TamerShlash, my pleasure :) Not sure why you revised the operator as exact match as the format may contain other characters except 'json'. I think REGEX match should be better and revised that. – Billy Chan May 14 '13 at 03:41
  • It gave me an error because it was `~=` not `=~`, I didn't know what the problem was because I'm not familiar with Ruby Regex, thanks again :) – Tamer Shlash May 14 '13 at 03:49
  • 1
    @TamerShlash, yes, that was a misspelling, sorry. Fixed in last edit. – Billy Chan May 14 '13 at 03:51
  • In Rails 4 the `request.format` is of type `Mime::Type` which doesn't interpret the `=~` operator correctly. Use `if request.format.to_s =~ /json/` instead. – Zajo Jul 30 '14 at 10:34
4

You can also do it in routes.rb, using constraints:

# Only allow HTML requests for all resources within the block
scope constraints: {format: :html} do
  resources :posts
  resources :comments
  get "/profile", to: "users#profile"
end
BrunoF
  • 3,239
  • 26
  • 39