Skip to content

Instantly share code, notes, and snippets.

@piotr-galas
Created December 13, 2017 15:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save piotr-galas/aecb26f6c93a9ef828a9b9cc11807ea3 to your computer and use it in GitHub Desktop.
Save piotr-galas/aecb26f6c93a9ef828a9b9cc11807ea3 to your computer and use it in GitHub Desktop.
require 'pry'
# TASK: Implement this class to make tests pass
class BaseClass
attr_reader :errors
VALIDATORS = %i[presence_of_validator numericality_validator].freeze
def self.validates_presence_of(name)
@presence_of_attr = name
end
def self.validates_numericality_of(name)
@numericality_of_attr = name
end
def valid?
@errors = []
invoke_all_validators
@errors.empty?
end
private
def invoke_all_validators
VALIDATORS.each { |validator_method |self.send(validator_method)}
end
def presence_of_validator
attr_name = self.class.instance_variable_get(:@presence_of_attr)
@errors.push("#{attr_name} can't be blank") if self.public_send(attr_name).nil? || self.public_send(attr_name).empty?
end
def numericality_validator
attr_name = self.class.instance_variable_get(:@numericality_of_attr)
@errors.push("#{attr_name} must be number") if !self.public_send(attr_name).is_a? Numeric
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment