Sha256: b992f54053b26796c00af9d1f3ec368bbf10413961f1c6a8eb7645dc30a8f4d1

Contents?: true

Size: 1.38 KB

Versions: 2

Compression:

Stored size: 1.38 KB

Contents

# encoding: utf-8
module Mongoid #:nodoc:
  module Criterion #:nodoc:
    # Complex criterion are used when performing operations on symbols to get
    # get a shorthand syntax for where clauses.
    #
    # Example:
    
    # {:opA => 'near', :opB => 'maxDistance' }
    # :location => { $near => [50,50], $maxDistance => 5 }
    class TwinOperators
      attr_accessor :key, :op_a, :op_b

      # Create the new complex criterion.
      def initialize(opts = {})
        @key = opts[:key]
        @op_a = opts[:op_a]
        @op_b = opts[:op_b]        
      end

      def make_hash v     
        v = extract_nearMax(v) if !v.kind_of?(Array) && op_b =~ /max/i
        {"$#{op_a}" => v.first, "$#{op_b}" => v.last }
      end

      def hash
        [@op_a, @op_b, @key].hash
      end

      def eql?(other)
        self == (other)
      end

      def ==(other)
        return false unless other.is_a?(self.class)        
        self.op_a == other.op_a && self.op_b == other.op_b && self.key == other.key 
      end
      
      protected
      
      protected

      def extract_nearMax(v)
        case v
        when Hash
          [v[:point], v[:distance]]
        else
          v.respond_to?(:point) ? [v.point, v.distance] : raise("Can't extract nearMax values from: #{v}, must have :point and :maxDistance methods or equivalent hash keys in Hash")
        end
      end
      
    end
  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
mongoid_geo-0.1.2 lib/mongoid/geo/criterion/twin_operators.rb
mongoid_geo-0.1.1 lib/mongoid/geo/criterion/twin_operators.rb