Reputation: 25112
Is there any way to ensure geo hash order using mongoid?
Currently I store it this way and do some magic in callback to ensure order:
field :location, type: Hash // { :lng => 33.33, :lat => 45 }
set_callback(:save, :before) do |doc|
if doc.location_changed?
doc.location = {lng: doc.location[:lng], lat: doc.location[:lat]}
end
end
May be there is some way to declare this Hash as class. I thought about Embeded Document, but it has _id.
Upvotes: 1
Views: 232
Reputation: 25112
It is possible to use mongoid custom field serialization for this.
Here is a good example: https://github.com/ricodigo/shapado/blob/master/app/models/geo_position.rb
Here is my own implementation that stores location in mongodb as array:
class LatLng
include Mongoid::Fields::Serializable
attr_reader :lat, :lng
def serialize(value)
return if value.nil?
if value.is_a?(self.class)
[value.lng.to_f, value.lat.to_f]
elsif value.is_a?(::Hash)
hash = value.with_indifferent_access
[hash['lng'].to_f, hash['lat'].to_f]
end
end
def deserialize(value)
return if value.nil?
value.is_a?(self.class) ? value : LatLng.new(value[1], value[0])
end
def initialize(lat, lng)
@lat, @lng = lat.to_f, lng.to_f
end
def [](arg)
case arg
when "lat"
@lat
when "lng"
@lng
end
end
def to_a
[lng, lat]
end
def ==(other)
other.is_a?(self.class) && other.lat == lat && other.lng == lng
end
end
Upvotes: 1