-
Notifications
You must be signed in to change notification settings - Fork 0
/
dirtyobjectfinal.rb
84 lines (74 loc) · 1.54 KB
/
dirtyobjectfinal.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
module DirtyObject
def initialize
@dirty_hash = Hash.new(Array.new(1))
@changed = false
end
def self.included(klass)
class << klass
def define_dirty_attributes(*args)
args.each do |param|
define_method("#{param}=") do |val|
@param = val
@changed = true
change_hash(val,param)
end
define_method(param) do
@param
end
define_method("#{param}_was") do
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.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
@dirty_hash.each { |key,values| values.shift }
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
puts u.email_was rescue puts 'undefined method'
puts u.age_was
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?