BeforeOr404 <img src=“https://travis-ci.org/eugenekorpan/before_or_404.png” alt=“Build Status” /> <img src=“https://codeclimate.com/github/eugenekorpan/before_or_404.png” />¶ ↑
Very simple gem that adds additional filter before_or_404
to ActionController::Base. It behaves just as a regular before_filter
but in a case when error raises in the filter it returns 404 page with 404 status.
1 Add this line to your application’s Gemfile:
gem 'before_or_404'
2 And then execute:
$ bundle
Let’s say you have a restful controller and appropriate url to edit a resource
http://bestsite.com/books/3/edit
And you have a before_filter
to avoid duplication
class BooksController < ApplicationController before_filter :find_book, :only => [:show, :edit, :update, :destroy] ... private def find_book @book = Book.find(params[:id]) end end
But what if I manually change the id in the url to one which is invalid
http://bestsite.com/books/just a super book/edit
Then this url considered to be invalid and hence user should see 404 page (“Page not found”) In this case you could do the next
class BooksController < ApplicationController before_filter :find_book, :only => [:show, :edit, :update, :destroy] ... private def page_not_found render 'public/404', status: 404 end def find_book @book = Book.find_by_id(params[:id]) @book || page_not_found end end
But this meens you should do this in every before_filter
where you find a resource by id which comes as a part of url. As alternative you could use before_or_404
instead of before_filter
.
class UsersController < ApplicationController before_or_404 :find_user, only: [:show, :edit, :destroy] ... private def find_user @user = User.find(params[:id]) end end
-
Fork it
-
Create your feature branch (
git checkout -b my-new-feature
) -
Commit your changes (
git commit -am 'Added some feature'
) -
Push to the branch (
git push origin my-new-feature
) -
Create new Pull Request