Skip to content

Instantly share code, notes, and snippets.

@joshmcarthur
Created April 7, 2014 04:51
Show Gist options
  • Save joshmcarthur/10014984 to your computer and use it in GitHub Desktop.
Save joshmcarthur/10014984 to your computer and use it in GitHub Desktop.
A controller concern to set the default format to JSON if none is provided, and enforce the requested formats
# app/controllers/concerns/json_default.rb
# USAGE:
# Simply include into a controller that should be restricted to JSON format:
# `include JSONDefault`
module JSONDefault
extend ActiveSupport::Concern
included do
before_action :set_default_format, :assert_valid_format!
end
private
# Private: Ensure that the format is set if none is provided.
#
# Examples:
#
# request format is JSON -> request format remains JSON
# request format is not set -> request format becomes JSON
# request format is XML -> request.format remains XML
#
# Returns the new request format
def set_default_format
request.format = 'json' unless params.key?(:format)
end
# Private: Assert that the format is set to JSON.
#
# If it is not, this will respond with a 406 Not Acceptable
def assert_valid_format!
raise ActionController::UnknownFormat unless request.format == 'json'
end
end
describe JSONDefault, type: :controller do
controller do
include JSONDefault
def index
render nothing: true
end
end
describe "ensure_default_format" do
context "no format" do
before { get :index }
it { request.format.should eq "json" }
end
context "json format" do
before { get :index, format: :json }
it { request.format.should eq "json" }
end
context "unknown format" do
before do
controller.stub(assert_valid_format!: true)
get :index, format: :xml
end
it { request.format.should eq 'xml' }
end
end
describe "assert_valid_format!" do
context "good format" do
it { expect { get :index }.to_not raise_error }
end
context "bad format" do
it { expect { get :index, format: :xml }.to raise_error(ActionController::UnknownFormat) }
end
end
end
.....
Finished in 0.10097 seconds
5 examples, 0 failures
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment