Class: MongoSearch::Sorter

Inherits:
Object
  • Object
show all
Defined in:
lib/mongo-search/sorter.rb

Instance Method Summary collapse

Constructor Details

#initialize(attr, opts = nil) ⇒ Sorter

Returns a new instance of Sorter.



3
4
5
# File 'lib/mongo-search/sorter.rb', line 3

def initialize(attr, opts = nil)
  @attr, @opts = attr, opts || {}
end

Instance Method Details

#call(params) ⇒ Object



7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
# File 'lib/mongo-search/sorter.rb', line 7

def call(params)
  sort = []

  if order_by = params[@attr] || @opts[:default]
    order_by.split(/\s*,\s*/).each do |attr_order|
      if attr_order =~ /([^\s]+)(?:\s*(asc|desc)?)$/
        attr_name, dir = $1, ($2 || :asc)
        sort << [:"#{attr_name}_ordenacao", :"#{dir}"]
        sort << [:"#{attr_name}", :"#{dir}"]
      else
        raise ArgumentError, "invalid sorting parameters: #{order_by}"
      end
    end
  end

  sort
end