Class: MongoFe::MongoDB::SearchDocuments

Inherits:
Object
  • Object
show all
Defined in:
lib/mongo_fe.rb

Instance Method Summary collapse

Constructor Details

#initialize(a_db, a_collection) ⇒ SearchDocuments

Returns a new instance of SearchDocuments.


41
42
43
44
# File 'lib/mongo_fe.rb', line 41

def initialize(a_db, a_collection)
  @db=a_db
  @collection=a_collection
end

Instance Method Details

#list(user_query, page = 1, per_page = 10) ⇒ Object


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
# File 'lib/mongo_fe.rb', line 46

def list(user_query, page=1, per_page=10)
  page_nr = page > 0 ? page : 1
  query   = user_query.nil? ? [{}, [], []] : user_query

  q = query.first.dup

  # verify if we have query containing a regexp
  q.each_pair do |k, v|
    if v.is_a?(String) && v.index(/^\//)
      q[k] = Regexp.new(v.gsub("/", ''))
    end
  end

  # quickly find the total hits
  count = @db.collection(@collection.name).find(q).count

  # get the docs and paginate.
  documents_list = WillPaginate::Collection.create(page_nr, per_page, count) do |pager|
    results = @collection.find( q,
                                :sort => sort_by(query.last),
                                :skip => ((page_nr-1) * per_page).to_i,
                                :limit => per_page,
                                :fields => just_these_fields(query[1])
                              ).to_a
    pager.replace(results)
  end

  [count, documents_list]
end