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
6
# File 'lib/mongo-search/sorter.rb', line 3

def initialize(attr, opts = nil)
  @attr, @opts = attr, opts || {}
  @mappings    = @opts[:mappings] || {}
end

Instance Method Details

#call(params) ⇒ Object



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

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.to_sym, ($2 || :asc).to_sym
        attr_name = @mappings[attr_name] if @mappings[attr_name]
        sort << [attr_name, dir]
      else
        raise ArgumentError, "invalid sorting parameters: #{order_by}"
      end
    end
  end

  sort
end