Module: Mongoid::SortedRelations

Extended by:
ActiveSupport::Concern
Defined in:
lib/mongoid/sorted_relations.rb

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.included(base) ⇒ Object



5
6
7
# File 'lib/mongoid/sorted_relations.rb', line 5

def self.included(base)
  base.after_initialize :freeze_relation_ids
end

Instance Method Details

#freeze_relation_idsObject



9
10
11
12
13
14
15
16
17
18
19
# File 'lib/mongoid/sorted_relations.rb', line 9

def freeze_relation_ids
  @cache_sorted_documents = {}
  @cache_sorted_ids = {}

  self.relations.each do |k,v|
    if [:has_many, :has_and_belongs_to_many].include? v.macro
      @cache_sorted_ids[v.key] = [self.send(v.key)].flatten.map{ |rid| rid.to_s }
      self.class.send(:define_method, "sorted_#{v.name}") { sorted_relation v }
    end
  end
end

#sorted_relation(relation) ⇒ Object



21
22
23
24
25
26
27
28
# File 'lib/mongoid/sorted_relations.rb', line 21

def sorted_relation(relation)
  if not @cache_sorted_documents[relation.name]
    documents = self.send(relation.name).sort_by { |x| @cache_sorted_ids[relation.key].index(x.id.to_s) }
    @cache_sorted_documents[relation.name] = Mongoid::FakeCriteria.new(documents)
  end

  return @cache_sorted_documents[relation.name]
end