Skip to content

Instantly share code, notes, and snippets.

@abdulsattar
Last active December 31, 2015 14:38
Show Gist options
  • Save abdulsattar/8001098 to your computer and use it in GitHub Desktop.
Save abdulsattar/8001098 to your computer and use it in GitHub Desktop.
Rails like presence validator
module PresenceValidator
attr_reader :errors
def self.included(base)
base.extend(ClassMethods)
end
private
def validate
@errors = []
options = self.class.options
attribute = self.class.attribute
value = self.send(self.class.attribute)
value.strip! if value && options[:strip]
if value.nil? || value.empty?
@errors.push([attribute.to_s, "#{attribute} is required."])
end
end
module ClassMethods
attr_reader :attribute, :options
def validates_presence_of(attribute, options)
options = {} unless options.is_a? Hash
default_options = {strip: false}
@options = default_options.merge(options)
@attribute = attribute
end
end
end
module BaseValidator
def self.included(base)
base.extend(ClassMethods)
end
def valid?
validate
@errors.empty?
end
module ClassMethods
VALIDATORS = {
presence: :validates_presence_of
}
def validates(attribute, validations)
validations.each do |validator, options|
self.send(VALIDATORS[validator], attribute, options) if options
end
end
end
end
class User
include BaseValidator
include PresenceValidator
attr_accessor :name
validates :name, presence: {strip: true}
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment