2015-04-17 36 views
0

我正在尋找一個好的rubygem進行參數驗證Rubygem的參數驗證

我想改善這種代碼重複。

例如,

class UsersController < ApplicationController 
    def create 
    handle_param_missing_exception unless params[:p1] && params[:p2] && params[:p2] ...and so on 
    handle_unvalid_format_exception unless params[:p1].is_email_format 
    handle_unvalid_format_exception unless params[:p2].is_integer_format 
    # and other huge validations 
    end 

    def update 
    handle_param_missing_exception unless params[:p1] && params[:p2] && params[:p2] ...and so on 
    handle_unvalid_format_exception unless params[:p1].is_email_format 
    handle_unvalid_format_exception unless params[:p2].is_integer_format 
    # and other huge validations 
    end 
end 

class ClientsController < ApplicationController 
    def create 
    handle_param_missing_exception unless params[:p1] && params[:p2] && params[:p2] ...and so on 
    handle_unvalid_format_exception unless params[:p1].is_email_format 
    handle_unvalid_format_exception unless params[:p2].is_integer_format 
    # and other huge validations 
    end 

    def update 
    handle_param_missing_exception unless params[:p1] && params[:p2] && params[:p2] ...and so on 
    handle_unvalid_format_exception unless params[:p1].is_email_format 
    handle_unvalid_format_exception unless params[:p2].is_integer_format 
    # and other huge validations 
    end 
end 

在我的項目,曾經動作有這種代碼。我想刪除所有的重複。

是否有一個良好的rubygem來處理呢?

如果沒有,想製作一個簡單的寶石這一點。

+0

使用強大的參數和控制器驗證是一個壞主意。相反,在模型中使用驗證更容易。 –

回答

1

有你檢查ActiveModel::Validations::ClassMethods

Ruby on Rails的提供了驗證一些內置的輔助方法,你並不需要使用寶石這一點。

任何一種格式驗證,你可以使用REGEXvalidates_format_of

class Person < ActiveRecord::Base 
    validates_format_of :email, :with => /\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\Z/i, :on => :create 
    validates_format_of :phone, with: /\A(\d{10}|\(?\d{3}\)?[-. ]\d{3}[-.]\d{4})\z/ 
end 

您可以檢查mail gem電子郵件驗證沒有正則表達式。

爲了驗證屬性的presence你可以定義爲:

class Person < ActiveRecord::Base 
    validates :name, :phone, :email, presence: true 
end 

有可用的驗證方法號碼,如:

您也可以創建自己的Custom Validators

FYI:驗證在model使用的是更好的主意,然後才能使用controller