Class: Gizmo::Search

Inherits:
BaseOperation show all
Defined in:
lib/gizmo/search.rb

Instance Attribute Summary

Attributes inherited from BaseOperation

#context

Instance Method Summary collapse

Methods inherited from BaseOperation

#create_response, #default_status, #initialize, #set_response_headers

Constructor Details

This class inherits a constructor from Gizmo::BaseOperation

Instance Method Details

#call(criteria, params = {}) ⇒ Gizmo::Response

Search for items.

Parameters:

  • criteria (Mongoid::Criteria)

    the criteria to use for searching the database

  • params (Hash) (defaults to: {})

    parameters used for searching

  • if (Proc)

    a block is given, it will be passed the criteria and params. It should return the result/data. note: the block will be used to perform the search.

Options Hash (params):

  • :term (String)

    the field to search

  • :query (String)

    the value used for searching

  • :num_items (Integer)

    the maximum number of items to return, default 10

  • :fuzzy (Boolean)

    true if fuzzy matching should be used, false otherwise, default to false

Returns:



16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
# File 'lib/gizmo/search.rb', line 16

def call(criteria, params={})
  response = create_response
  if block_given?
    response.data = yield criteria, params
  else
    term = params[:term]
    query = params[:query]
    num_items = (params[:num_items] || 10).to_i
    num_items = 10 if num_items > 100 || num_items < 1

    fuzzy = !!((params[:fuzzy] || "") =~ /true/i)
    if fuzzy
      query = /#{query}/i
    end

    response.data = criteria.where(term => query).limit(num_items)
  end
  response
end