Module: Mongoid::Alphadog::ClassMethods

Defined in:
lib/mongoid/alphadog.rb

Instance Method Summary collapse

Instance Method Details

#alphabetize_on(*fields) ⇒ Object



7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
# File 'lib/mongoid/alphadog.rb', line 7

def alphabetize_on(*fields)
  return false unless fields.present?
  fields.map(&:to_s).each { |f|
    symbol = "#{f}_loweralpha".to_sym
    field(symbol, type: String)
    index({symbol: 1})
    meth = "set_#{f}_loweralpha".to_sym
    class_eval "      before_save do\n        self.send(\"\#{symbol}=\".to_sym, self.send(f.to_sym).try(:downcase))\n      end\n    RUBY\n  }\n  \n  instance_eval do\n   scope :alphabetized_by, lambda { |*alpha_fields|\n      aorder = alpha_fields.map do |alpha|\n        [[alpha.to_s, 'loweralpha'].join('_').to_sym, :asc]\n      end\n      order_by(aorder)\n    }\n  end\nend\n"