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
|
# File 'lib/cleaning_cloth/active_record_extension.rb', line 8
def clean! opts=nil
opts ||= default_clean_options
opts[:max_level] ||= 3
return if opts[:max_level] <= 0
exceptions = Array(opts[:except] || []) + [:id, :create_at, :updated_at]
includes = Array(opts[:includes] || []) exceptions.reject! {|item| includes.include?(item) }
all_attributes = self.attributes || {}
all_associations = self.class.reflect_on_all_associations
assoc_exceptions = all_associations.map {|assoc| assoc.foreign_key }
exceptions += assoc_exceptions
exceptions.uniq!
exceptions.compact!
exceptions.map! &:to_sym
unless exceptions.include? :all_associations
all_associations.reject! {|item| exceptions.include?(item.name)}
all_associations.each do |assoc|
assoc_name = assoc.name
data = self.send(assoc_name)
next unless data.present?
Array(data).each do |obj|
obj_opts = opts.deep_fetch(assoc_name, {})
obj_opts[:max_level] = opts[:max_level] - 1
obj.clean! obj_opts
end
end
end
all_attributes.each do |attr_name, attr_value|
attr_name = attr_name.to_sym
next if exceptions.include?(attr_name) && attr_value == self.send(attr_name)
value = exceptions.include?(attr_name) ? attr_value : nil
self.send("write_attribute", attr_name, value)
end
self
end
|