-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmacros.rb
72 lines (56 loc) · 1.33 KB
/
macros.rb
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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
class Proform
def self.attributes
@attributes ||= []
end
def self.validations
@validations ||= {}
end
def self.attribute(name)
attributes << name
end
def self.validates(attr, params)
validations[attr] = params
end
attr_reader :model, :errors, :params
def initialize(model)
@model = model
@errors = Hash.new { |h, k| h[k] = [] }
end
def validate(params)
@params = params.keep_if { |attr| self.class.attributes.include?(attr) }
self.class.validations.each do |attr, validations|
validations.each do |type, value|
if type == :presence && value == true
errors[attr] << "can't be blank" unless params[attr]
end
end
end
valid?
end
def valid?
errors.empty?
end
def apply
return false unless valid?
return true unless params
params.each {|attr, val| model.public_send("#{attr}=", val)}
end
end
class MyForm < Proform
attribute :title
attribute :description
validates :title, presence: true
end
Product = Struct.new(:title, :description)
p model = Product.new('Ruby blog', 'Description')
form = MyForm.new(model)
p form.validate(description: 'Test')
p form.errors
p form.apply
p model
form = MyForm.new(model)
p form.validate(title: 'test.ru', description: 'Ruby blog')
p form.valid?
p form.errors
p form.apply
p model