Skip to content

Commit 63b7cba

Browse files
committed
use if/elsif/else logic to force use of == operators
Since `request.format` is of type `Mime::Type` which implements a `==` operator so that it is easy to compare to a symbol, we need to use an if statement so we can ensure that `Mime::Type`'s `==` operator is called instead of `Symbol`'s. Also update the spec to use `Mime::Type` objects so we're not masking what is happening.
1 parent 683db03 commit 63b7cba

File tree

2 files changed

+14
-12
lines changed

2 files changed

+14
-12
lines changed

lib/kracken/controllers/authenticatable.rb

Lines changed: 7 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -37,15 +37,13 @@ def authenticate_user
3737

3838
def authenticate_user!
3939
check_token_expiry!
40-
unless user_signed_in?
41-
case request.format
42-
when :json
43-
render json: {error: '401 Unauthorized'}, status: :unauthorized
44-
when :js
45-
head :unauthorized
46-
else
47-
redirect_to_sign_in
48-
end
40+
return if user_signed_in?
41+
if request.format == :json
42+
render json: {error: '401 Unauthorized'}, status: :unauthorized
43+
elsif request.format == :js
44+
head :unauthorized
45+
else
46+
redirect_to_sign_in
4947
end
5048
end
5149

spec/kracken/controllers/authenticatable_spec.rb

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -43,8 +43,12 @@ class ControllerDouble < BaseControllerDouble
4343
end
4444

4545
context "when no users are logged in" do
46+
let(:html) { Mime::Type.lookup("text/html") }
47+
let(:json) { Mime::Type.lookup("application/json") }
48+
let(:js) { Mime::Type.lookup("application/javascript") }
49+
4650
it "#authenticate! redirects to root_url for format html" do
47-
allow(controller).to receive(:request).and_return(double(format: :html, fullpath: nil))
51+
allow(controller).to receive(:request).and_return(double(format: html, fullpath: nil))
4852
allow(controller).to receive(:redirect_to)
4953

5054
controller.authenticate_user!
@@ -57,7 +61,7 @@ class ControllerDouble < BaseControllerDouble
5761
end
5862

5963
it "#authenticate! doesn't redirect for format json" do
60-
allow(controller).to receive(:request).and_return(double(format: :json, fullpath: nil))
64+
allow(controller).to receive(:request).and_return(double(format: json, fullpath: nil))
6165
allow(controller).to receive(:redirect_to)
6266
allow(controller).to receive(:render)
6367

@@ -68,7 +72,7 @@ class ControllerDouble < BaseControllerDouble
6872
end
6973

7074
it "#authenticate! doesn't redirect for format js" do
71-
allow(controller).to receive(:request).and_return(double(format: :js, fullpath: nil))
75+
allow(controller).to receive(:request).and_return(double(format: js, fullpath: nil))
7276
allow(controller).to receive(:redirect_to)
7377
allow(controller).to receive(:head)
7478

0 commit comments

Comments
 (0)