lib/builder/mongo_helpers.rb in sinatra_resource-0.4.4 vs lib/builder/mongo_helpers.rb in sinatra_resource-0.4.5

- old
+ new

@@ -20,11 +20,46 @@ def check_related?(parent, child_assoc, child_id) children = parent.send(child_assoc) find_child!(children, child_id) true end + + # Find +model+ documents: find all documents if no params, otherwise + # find selected documents. + # + # @param [Class] model + # a class that includes MongoMapper::Document + # + # @return [Integer] + def count_documents(model) + conditions = params.empty? ? {} : make_conditions(params, model) + model.count(conditions) + end + def count_nested_documents(parent, child_assoc, child_model) + # + # This code needs significant improvement. + # It is copy and pasted from find_nested_documents! + # + documents = if child_model.embeddable? + children = parent.send(child_assoc) + if params.empty? + children + else + select_by(children, make_conditions(params, child_model)) + end + else + children = if params.empty? + child_model.all + else + child_model.all(make_conditions(params, child_model)) + end + select_related(parent, child_assoc, children) + end + documents.length + end + # Create a document from params. If not valid, returns 400. # # @param [Class] model # a class that includes MongoMapper::Document # @@ -197,21 +232,24 @@ unless document error 404, convert(body_for(:not_found)) end document end - + # Find +model+ documents: find all documents if no params, otherwise # find selected documents. # # @param [Class] model # a class that includes MongoMapper::Document # # @return [Array<MongoMapper::Document>] - def find_documents!(model) - return(model.all) if params.empty? - model.all(make_conditions(params, model)) + def find_documents!(model, page, items_per_page) + conditions = params.empty? ? {} : make_conditions(params, model) + model.all(conditions.merge({ + :skip => items_per_page * (page - 1), + :limit => items_per_page + })) end # Find nested +child_model+ documents: find all documents if no # params, otherwise find selected documents. # @@ -224,11 +262,15 @@ # a class that includes either: # * MongoMapper::Document # * MongoMapper::EmbeddedDocument # # @return [Array<MongoMapper::Document>] - def find_nested_documents!(parent, child_assoc, child_model) + def find_nested_documents!(parent, child_assoc, child_model, page, items_per_page) + # + # TODO: handle page parameter + # TODO: handle items_per_page parameter + # documents = if child_model.embeddable? children = parent.send(child_assoc) if params.empty? children else @@ -242,10 +284,10 @@ end select_related(parent, child_assoc, children) end end - # Delegates to application, who should use custom logic to related + # Delegates to application, who should use custom logic to relate # +parent+ and +child+. # # @param [MongoMapper::Document] parent # a class that includes MongoMapper::Document #