-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathValidate.rb
More file actions
50 lines (40 loc) · 1010 Bytes
/
Copy pathValidate.rb
File metadata and controls
50 lines (40 loc) · 1010 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
module Validate
def self.included(base)
base.extend(ClassMethods)
base.include(InstanceMethods)
end
module ClassMethods
def validations
@validations ||= []
end
def validate(name, type, *param)
validations << { name: name, type: type, params: param }
end
end
module InstanceMethods
def validate!
self.class.validations.each do |value|
valid = "valid_#{value[:type]}"
param = value[:param]
value = instance_variable_get("@#{value[:name]}".to_sym)
send(valid, value, *param)
end
end
def valid?
validate!
true
rescue
false
end
private
def valid_presence(value)
raise "Value can't be nill or empty" if value.nil? || value.empty?
end
def valid_format(value, format)
raise "invalid format of value" if value.nil? || value !~ format
end
def valid_type(value, type)
raise "invalid type of value" unless value.is_a?(type)
end
end
end