Module: Olc::ClassMethods

Defined in:
lib/rails/olc.rb

Constant Summary collapse

OLC_OPTIONS =

Default Olc options

{
  field: 'open_location_code',
  latitude: 'latitude',
  longitude: 'longitude',
  code_length: 10
}

Instance Method Summary collapse

Instance Method Details

#has_olc(options = {}) ⇒ Object

Define before_save callback to generate olc code.

Examples:


has_olc
# or
has_olc(field: 'olc', latitude: 'lat', longitude: 'lng', code_length: 10)


33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
# File 'lib/rails/olc.rb', line 33

def has_olc(options = {})
  options = OLC_OPTIONS.merge(options)

  if defined?(Mongoid)
    field options[:field], type: String
  end

  before_save do |obj|
    lat_field = options[:latitude]
    lng_field = options[:longitude]

    changed_attrs = obj.changed_attributes

    if changed_attrs.key?(lat_field) || changed_attrs.key?(lng_field)
      if obj[lat_field] && obj[lng_field]
        obj[options[:field]] = obj.olc_encode(options[:code_length])
      else
        obj[options[:field]] = nil
      end
    end
  end

  class_eval "    def olc_encode(code_length = nil)\n      OpenLocationCode.encode(\#{options[:latitude]}, \#{options[:longitude]}, code_length)\n    end\n\n    def olc_decode\n      OpenLocationCode.decode(\#{options[:field]})\n    end\n  RUBY\nend\n", __FILE__, __LINE__ + 1