Skip to content

Instantly share code, notes, and snippets.

@cotocisternas
Created January 31, 2019 15:58
Show Gist options
  • Select an option

  • Save cotocisternas/2c3dcb1cd7fbbff76a0614088f4920f2 to your computer and use it in GitHub Desktop.

Select an option

Save cotocisternas/2c3dcb1cd7fbbff76a0614088f4920f2 to your computer and use it in GitHub Desktop.
rails custom validations

Rails Custom Validations

app/models/doc.rb

# 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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment