# frozen_string_literal: true
class Doc
include Mongoid ::Document
include Mongoid ::Timestamps
field :name , type : String
field :rut , type : String
field :md5 , type : String
field :mime_type , type : String , default : 'application/pdf'
field :size , type : String
field :pdf , type : String
embedded_in :document
validates :rut , presence : true , rut : true
validates_with PdfValidator
end
app/validators/pdf_validator.rb
# frozen_string_literal: true
class PdfValidator < ActiveModel ::Validator
def validate ( record )
if record . pdf
pdf = Base64 . decode64 record . pdf
md5 = Digest ::MD5 . hexdigest pdf
mime_type = Parsers ::DetectMime . open pdf
size = pdf . size
record . errors . add ( :md5 , "missmatch, expected #{ md5 } " ) unless md5 . casecmp ( record . md5 ) . zero?
record . errors . add ( :mime_type , "missmatch, expected #{ mime_type } " ) unless mime_type . casecmp ( record . mime_type ) . zero?
record . errors . add ( :size , "missmatch, expected #{ size } " ) unless size . to_i == record . size . to_i
else
record . errors . add ( :md5 , 'missmatch' )
record . errors . add ( :mime_type , 'missmatch' )
record . errors . add ( :size , 'missmatch' )
end
end
end
app/validators/rut_validator.rb
# frozen_string_literal: true
class RutValidator < ActiveModel ::EachValidator
def validate_each ( record , attribute , value )
return unless value
record . errors . add ( attribute , 'invalid rut' ) unless RutCL . is_valid? ( value )
end
end