Module: Mongoid::Fields::ClassMethods

Defined in:
lib/mongoid/geo/fields.rb

Overview

:nodoc

Instance Method Summary collapse

Instance Method Details

#create_accessors(name, meth, options = {}) ⇒ Object



5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
# File 'lib/mongoid/geo/fields.rb', line 5

def create_accessors(name, meth, options = {})
  generated_field_methods.module_eval do
    define_method(meth) { read_attribute(name) }

    if options[:type] == Array && options[:geo]            
      lat_meth = options[:lat] || "lat"
      lng_meth = options[:lng] || "lng"

      define_method(lat_meth) { read_attribute(name)[0] }
      define_method(lng_meth) { read_attribute(name)[1] }
                  
      define_method "#{lat_meth}=" do |value|
        send(name)[0] = value
      end            
      define_method "#{lng_meth}=" do |value|
        send(name)[1] = value
      end            
    end

    define_method("#{meth}=") do |value|
      if options[:type] == Array && options[:geo]
        value = case value
        when String
          value.split(",").map(&:to_f)
        when Array
          value.compact.extend(Mongoid::Geo::Point).to_points
        else
          !value.nil? ? value.extend(Mongoid::Geo::Point).to_point : value
        end
        value = value[0..1] if !value.nil?
      end            
      write_attribute(name, value) 
    end

    define_method("#{meth}?") do
      attr = read_attribute(name)
      (options[:type] == Boolean) ? attr == true : attr.present?
    end
  end
end