Skip to content

Instantly share code, notes, and snippets.

View dimasusername's full-sized avatar
🏇

Dmitrii Kharlamov dimasusername

🏇
View GitHub Profile
class Supplier
include Mongoid::Document
field(:name, type: String)
field(:_id, default: -> { name.parameterize if self })
end
class Location
include Mongoid::Document
index(loc: '2dsphere')
field(:number, type: Integer)
# supplier id
field(:sid, type: String)
# coordinates
field(:loc, type: Array)
namespace 'import' do
task 'locations' do
locations = App.mongo_db.collection('locations')
locations.insert(
number: 1,
sid: 'supplier-one',
loc: [8, 10]
)
locations.insert(
number: 2,
class App < Sinatra::Base
configure do
# Let's connect to MongoDB
begin
mongo_db = Mongo::Connection.new.db('data-test')
set :mongo_db, mongo_db
rescue Mongo::ConnectionFailure
set :mongo_db, {}
end
Mongoid.load!('mongoid.yml')
@dimasusername
dimasusername / app.rb
Created June 29, 2016 21:38
Suppliers
get '/suppliers' do
Supplier.all.to_json
end
@dimasusername
dimasusername / app.rb
Last active June 29, 2016 21:52
Locations
get '/locations' do
lat = params.fetch(:lat, 0).to_f
lng = params.fetch(:lng, 0).to_f
distance = params[:distance].to_i * 1.61 * 1000
query = {
loc: {
:$near => {
:$geometry => {
type: 'Point',
[
{
"_id": "supplier-one",
"name": "Supplier One"
},
{
"_id": "supplier-two",
"name": "Supplier Two"
}
]
[
{
"_id": {
"$oid": "57743e43f0f32e48e4000004"
},
"number": 2,
"rid": "supplier-two",
"loc": [2,3]
}
]
get '/suppliers-with-locations' do
lat = params.fetch(:lat, 0).to_f
lng = params.fetch(:lng, 0).to_f
distance = params[:distance].to_i * 1.61 * 1000
query = {
loc: {
:$near => {
:$geometry => {
type: 'Point',
supplier_ids = locations.map { |location| location['sid'] }.uniq
locations.rewind!
suppliers = settings.mongo_db.collection('suppliers').find(
_id: {
:$in => supplier_ids
}
)