-
Notifications
You must be signed in to change notification settings - Fork 0
/
denormalize.rb
37 lines (28 loc) · 847 Bytes
/
denormalize.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
module Mongoid
module Denormalize
extend ActiveSupport::Concern
included do
class_attribute :denormalizations
# add callback to save tags index
before_save :do_denormalize, :if => :denormalizations
end
def do_denormalize
return if self.denormalizations.blank?
self.denormalizations.each do |field, subfields|
next unless self.respond_to? field
linked = self.send field
subfields.each do |subfield|
self["#{field}_#{subfield}"] = linked.send(subfield) if linked.respond_to? subfield
end
end
end
module ClassMethods
def denormalize(*args, options)
args.each do |subfield|
field "#{options[:from]}_#{subfield}"
end
(self.denormalizations ||= {})[options[:from]] = args
end
end
end
end