-
Notifications
You must be signed in to change notification settings - Fork 0
/
dirtyobjectmodified.rb
80 lines (68 loc) · 1.54 KB
/
dirtyobjectmodified.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
module DirtyObject
attr_accessor :dirty_hash, :name_was, :age_was
def initialize
@dirty_hash = Hash.new { |hash, key| hash[key] = [] }
end
def self.included(klass)
class << klass
def define_dirty_attributes(*args)
args.each do |param|
instance_variable_set("@#{ param }_was", nil)
define_method("#{ param }=") do |val|
instance_variable_set("@#{ param }", val)
change_hash(val, param)
end
define_method("#{ param }") do
instance_variable_get("@#{ param }")
end
end
end
end
end
def change_hash(val, param)
check = instance_eval("#{ param }_was")
if val.eql? check
@dirty_hash.delete(param)
else
@dirty_hash[param].push(check, val)
end
end
def changes
@dirty_hash
end
def changed?
@dirty_hash.any?
end
def save
@dirty_hash.each { |key, _values| instance_variable_set("@#{ key }_was", public_send(key)) }
@dirty_hash.clear
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?
puts u.changes
puts u.name_was ? u.name_was : 'nil'
puts u.email_was rescue puts 'undefined method'
puts u.age_was ? u.age_was : 'nil'
puts u.save
puts u.changed?
puts u.changes
u.name = 'New name'
u.age = 31
puts u.changes
puts u.name_was
u.name = 'Akhil'
puts u.changes
puts u.changed?
u.age = 30
puts u.changes
puts u.changed?