-
Notifications
You must be signed in to change notification settings - Fork 0
/
newdirtyobject.rb
96 lines (73 loc) · 1.83 KB
/
newdirtyobject.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
88
89
90
91
92
93
94
95
module DirtyObject
@@dirty_hash = Hash.new(Array.new(1))
@@changed = false
def self.included(klass)
class << klass
def define_dirty_attributes(*args)
args.each do |param|
class_eval %{
def #{param}=(val)
@@changed = true
@#{param}=val
change_hash(val,'#{param}')
end
def #{param}
@#{param}
end
def #{param}_was
return 'nil' unless @@dirty_hash['#{param}'][0]
@@dirty_hash['#{param}'][0]
end
}
end
end
end
end
def change_hash(val,param)
if @@dirty_hash[param][0] == val || @@dirty_hash[param][1] == val
@@dirty_hash.delete(param)
@@changed = false if @@dirty_hash.empty?
else
@@dirty_hash[param] += [val]
@@dirty_hash[param].shift if @@dirty_hash[param].length > 2
end
end
def changes
return {} unless changed?
@@dirty_hash
end
def changed?
@@changed
end
def save
@@changed = false
true
end
end
class User
include DirtyObject
attr_accessor :name, :age, :email
define_dirty_attributes :name, :age
end
u = User.new
u.name = 'Akhil'
u.email = '[email protected]'
u.age = 30
puts u.changed? #=> true
puts u.changes #=> { name: [nil, 'Akhil], age: [nil, 30] }
puts u.name_was #=> nil
puts u.email_was rescue puts 'undefined method'
puts u.age_was #=> nil
puts u.save #=> true
puts u.changed? #=> false
puts u.changes #=> {}
u.name = 'New name'
u.age = 31
puts u.changes #=> {name: ['Akhil', 'New name'], age: [30, 31]}
puts u.name_was #=> 'Akhil'
u.name = 'Akhil'
puts u.changes #=> {age: [30, 31]}
puts u.changed? #=> true
u.age = 30
puts u.changes #=> {}
puts u.changed? #=> false