-
Notifications
You must be signed in to change notification settings - Fork 0
/
mystoreworking.rb
87 lines (71 loc) · 1.65 KB
/
mystoreworking.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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
require 'forwardable'
module MyObjectStore
def self.included(klass)
class << klass
extend Forwardable
attr_accessor :array_object, :find_by, :validate
def_delegator :@array_object, :collect
def_delegator :@array_object, :count
def validate_presence_of(*args)
args.each do |name|
define_method("is_exist_#{name}") do
return true if eval(name.to_s)
false
end
end
end
end
klass.find_by.each do |name|
klass.instance_eval %{
def find_by_#{name}(value)
array_object.find { |x| x.#{name}.eql? value }
end
}
end
end
def save
validate
self.class.array_object << self if @errors.empty?
return "created object #{self}" if @errors.empty?
@errors
end
end
class Play
@find_by = [:fname, :lname, :age, :email]
@validate = [:fname, :age]
@array_object = []
include MyObjectStore
include Enumerable
attr_accessor :fname ,:lname ,:age ,:email
validate_presence_of :fname ,:age
def initialize
@errors = Hash.new(Array.new)
end
def validate
@errors['age'] += ['Age should be a integer'] unless age.is_a?(Integer)
self.class.validate.each do |param|
@errors[param] = "#{param} must exist" unless eval("is_exist_#{param}")
end
end
end
p2 = Play.new
p2.fname = "abc"
p2.lname = "def"
p2.email = "[email protected]"
p2.age = 1
p3 = Play.new
p3.fname = "bsd"
p3.age = 12
p4 = Play.new
p4.fname ="bc"
p5 = Play.new
p5.age ="bc"
# p5.fname = "ppd"
puts p2.save
puts p3.save
puts p4.save
puts p5.save
p Play.collect
p Play.count
p Play.find_by_fname('abc')
p Play.find_by_lname('def')