jeudi 13 août 2015

How to break Rails application and return 404 as JSON

Rails application working as API service. I use mongoid

In a controller i write now:

class UsersController < ApplicationController
  def show
    @user = User.find params[:user_id]
    unless @user
      render json: { error: I18n.t('user.messages.not_found') }, status: :not_found
      return
    end
    # ... some actions with @user object 
  end
end

I need make code cleaner and move this code in module. I assume that the code in controller may look like this:

class UsersController < ApplicationController
  def show
    @user = User.find params[:user_id]
    not_found? @user

    # ... some actions with @user object
  end
end

or like this

class UsersController < ApplicationController
  def show
    @user = found? User, params[:user_id]

    # ... some actions with @user object
  end
end

One of example how it can work is Pundit gem (http://ift.tt/1cmAaug). In my controller i write:

...
def index
  authorize User, :index?
  @users = User.all
end
...

if user hasn't access to this page then Pundit raise exception and return to client error message with 401 http code.

What is better way to refactor my code to make controllers cleaner?



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire