Class: MongoMapper::FinderOptions

Inherits:
Object
  • Object
show all
Defined in:
lib/mongo_mapper/finder_options.rb

Constant Summary collapse

OptionKeys =
[:fields, :select, :skip, :offset, :limit, :sort, :order]

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(options) ⇒ FinderOptions

Returns a new instance of FinderOptions.

Raises:

  • (ArgumentError)


47
48
49
50
51
52
53
54
55
56
57
58
59
60
# File 'lib/mongo_mapper/finder_options.rb', line 47

def initialize(options)
  raise ArgumentError, "FinderOptions must be a hash" unless options.is_a?(Hash)
  
  options = options.symbolize_keys
  @options, @conditions = {}, options.delete(:conditions) || {}
  
  options.each_pair do |key, value|
    if OptionKeys.include?(key)
      @options[key] = value
    else
      @conditions[key] = value
    end
  end
end

Instance Attribute Details

#optionsObject (readonly)

Returns the value of attribute options.



3
4
5
# File 'lib/mongo_mapper/finder_options.rb', line 3

def options
  @options
end

Class Method Details

.field_normalized(field) ⇒ Object



37
38
39
40
41
42
43
# File 'lib/mongo_mapper/finder_options.rb', line 37

def self.field_normalized(field)
  if field.to_s == 'id'
    :_id
  else
    field
  end
end

.to_mongo_criteria(conditions, parent_key = nil) ⇒ Object



5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
# File 'lib/mongo_mapper/finder_options.rb', line 5

def self.to_mongo_criteria(conditions, parent_key=nil)
  criteria = {}
  conditions.each_pair do |field, value|
    field = field_normalized(field)
    case value
      when Array
        operator_present = field.to_s =~ /^\$/            
        criteria[field] = if operator_present
                            value
                          else
                            {'$in' => value}
                          end
      when Hash
        criteria[field] = to_mongo_criteria(value, field)
      else            
        criteria[field] = value
    end
  end
  
  criteria
end

.to_mongo_options(options) ⇒ Object



27
28
29
30
31
32
33
34
35
# File 'lib/mongo_mapper/finder_options.rb', line 27

def self.to_mongo_options(options)
  options = options.dup
  {
    :fields => to_mongo_fields(options.delete(:fields) || options.delete(:select)),
    :skip   => (options.delete(:skip) || options.delete(:offset) || 0).to_i,
    :limit  => (options.delete(:limit) || 0).to_i,
    :sort   => options.delete(:sort) || to_mongo_sort(options.delete(:order))
  }
end

Instance Method Details

#criteriaObject



62
63
64
# File 'lib/mongo_mapper/finder_options.rb', line 62

def criteria
  self.class.to_mongo_criteria(@conditions)
end

#to_aObject



70
71
72
# File 'lib/mongo_mapper/finder_options.rb', line 70

def to_a
  [criteria, options]
end