2013-07-09 30 views
1

我有用於移動設備的會話控制器。我想稍微重構它,例如因爲我的會話控制器是Devise::SessionsController的子類,我不得不從BaseController複製錯誤方法。如何從基於Devise的會話控制器中刪除重複的方法?

class Api::V1::SessionsController < Devise::SessionsController 
    include Devise::Controllers::Helpers 
    prepend_before_filter :require_no_authentication, only: [:create] 
    skip_load_and_authorize_resource 
    before_filter :ensure_params_exist, only: [:create] 

    respond_to :json 

    def create 
    if user_find params[:user][:member_id] 
     self.resource = warden.authenticate!(auth_options) 
     sign_in(resource_name, resource) 
     resource.reset_authentication_token! 
     resource.save! 
    else 
     error :not_found 
    end 
    end 

    def destroy 
    sign_out(resource_name) 
    end 

    private 

    def user_find(id) 
    User.find_by member_id: id 
    end 

    def ensure_params_exist 
    unless params[:user] 
     error :bad_request 
    end 
    end 

    def error type, context=nil 
    render json: { message: error_message(type, context) }, status: type 
    end 

    def error_message type, context 
    scope = [:api, :error, self.controller_name.to_sym] 
    scope.push context if context 
    t(type, scope: scope) 
    end 

end 

class Api::V1::BaseController < ApplicationController 
    load_and_authorize_resource 

    respond_to :json 

    rescue_from CanCan::AccessDenied do |exception| 
    render_status :unauthorized 
    end 

    private 

    def error type, context=nil 
    render json: {message: error_message(type, context)}, status: type 
    end 

    def error_message type, context 
    scope = [:api, :error, self.controller_name.to_sym] 
    scope.push context if context 
    t(type, scope: scope) 
    end 

    def render_status state 
    render status: state, json: {} 
    end 
end 
+0

也許有在這裏使用Rails的4所擔憂的方法嗎? – tomekfranek

回答

1

我建議將通用方法提取到模塊幷包含它。

module CommonMethods 
    def self.included(controller) 
    controller.send :error_message, :error 
    end 

    def error type, context=nil 
    render json: {message: error_message(type, context)}, status: type 
    end 

    def error_message type, context 
    scope = [:api, :error, self.controller_name.to_sym] 
    scope.push context if context 
    t(type, scope: scope) 
    end 
end 

而就包括它include CommonMethods在控制器

+1

沒有'self'' – tomekfranek