Skip to content

Instantly share code, notes, and snippets.

@aliou
Last active August 13, 2018 19:57
Show Gist options
  • Save aliou/b07b8ac414a6b805d0b6e2f57251ef64 to your computer and use it in GitHub Desktop.
Save aliou/b07b8ac414a6b805d0b6e2f57251ef64 to your computer and use it in GitHub Desktop.

While going source spelunking, I came across this piece of code in Rails' ActiveModel:

key = "#{key.to_s.camelize}Validator"

begin
  validator = key.include?("::".freeze) ? key.constantize : const_get(key)
rescue NameError
  raise ArgumentError, "Unknown validator: '#{key}'"
end

Rails source: active_model/validations/validates.rb

This means that you can namespace your custom validators and use them like this:

# lib/internal/email_validator.rb
module Internal
  class EmailValidator
    def validate_each(record, attribute, value)
      return if value.ends_with?('@private_domain.com')

      record.errors.add(attribute, 'not from private domain')
    end
  end
end

# app/models/admin.rb
class Admin < ApplicationRecord
  validates :email, 'internal/email': true
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment