Adds document_number-related constraints to User

This commit is contained in:
kikito
2015-10-08 15:19:11 +02:00
parent 5f74528f12
commit d351daedd4
2 changed files with 22 additions and 0 deletions

View File

@@ -25,6 +25,7 @@ class User < ActiveRecord::Base
validates :username, presence: true, unless: :organization?
validates :username, uniqueness: true, unless: :organization?
validates :document_number, uniqueness: { scope: :document_type }, allow_nil: true
validate :validate_username_length
validates :official_level, inclusion: {in: 0..5}
@@ -44,6 +45,8 @@ class User < ActiveRecord::Base
scope :for_render, -> { includes(:organization) }
scope :by_document, -> (document_type, document_number) { where(document_type: document_type, document_number: document_number) }
before_validation :clean_document_number
def self.find_for_oauth(auth, signed_in_resource = nil)
# Get the identity and user if they exist
identity = Identity.find_for_oauth(auth)
@@ -171,6 +174,10 @@ class User < ActiveRecord::Base
private
def clean_document_number
self.document_number = self.document_number.gsub(/[^a-z0-9]+/i, "").upcase unless self.document_number.blank?
end
def validate_username_length
validator = ActiveModel::Validations::LengthValidator.new(
attributes: :username,

View File

@@ -287,4 +287,19 @@ describe User do
end
describe "document_number" do
it "should upcase document number" do
user = User.new({document_number: "x1234567z"})
user.valid?
expect(user.document_number).to eq("X1234567Z")
end
it "should remove all characters except numbers and letters" do
user = User.new({document_number: " 12.345.678 - B"})
user.valid?
expect(user.document_number).to eq("12345678B")
end
end
end