mongo_geo 0.1.0

Sign up to get free protection for your applications and to get access to all the features.
data/.document ADDED
@@ -0,0 +1,5 @@
1
+ README.rdoc
2
+ lib/**/*.rb
3
+ bin/*
4
+ features/**/*.feature
5
+ LICENSE
data/.gitignore ADDED
@@ -0,0 +1,21 @@
1
+ ## MAC OS
2
+ .DS_Store
3
+
4
+ ## TEXTMATE
5
+ *.tmproj
6
+ tmtags
7
+
8
+ ## EMACS
9
+ *~
10
+ \#*
11
+ .\#*
12
+
13
+ ## VIM
14
+ *.swp
15
+
16
+ ## PROJECT::GENERAL
17
+ coverage
18
+ rdoc
19
+ pkg
20
+
21
+ ## PROJECT::SPECIFIC
data/LICENSE ADDED
@@ -0,0 +1,20 @@
1
+ Copyright (c) 2009 Michael Parrish
2
+
3
+ Permission is hereby granted, free of charge, to any person obtaining
4
+ a copy of this software and associated documentation files (the
5
+ "Software"), to deal in the Software without restriction, including
6
+ without limitation the rights to use, copy, modify, merge, publish,
7
+ distribute, sublicense, and/or sell copies of the Software, and to
8
+ permit persons to whom the Software is furnished to do so, subject to
9
+ the following conditions:
10
+
11
+ The above copyright notice and this permission notice shall be
12
+ included in all copies or substantial portions of the Software.
13
+
14
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
15
+ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
16
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
17
+ NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
18
+ LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
19
+ OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
20
+ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
data/README.markdown ADDED
@@ -0,0 +1,38 @@
1
+ # mongo_geo
2
+
3
+ mongo_geo is a plugin for MongoMapper that exposes the [GeoSpatial indexing features](http://www.mongodb.org/display/DOCS/Geospatial+Indexing) in MongoDb.
4
+
5
+ Currently, I'm only developing against Ruby 1.9.1 so other versions may be flakey.
6
+
7
+ ## Usage
8
+ ### On the model
9
+ class TestAsset
10
+ include MongoMapper::Document
11
+ plugin GeoSpatial
12
+
13
+ geo_key :coords, Array
14
+ end
15
+
16
+ ### [Plucky](http://github.com/jnunemaker/plucky) style queries:
17
+ TestAsset.where(:coords.near => [50, 50]).limit(10).to_a
18
+ TestAsset.where(:coords.within => { "$center" => [[50, 50], 10] }).to_a # "$center" => [center, radius]
19
+ TestAsset.where(:coords.within => { "$box" => [ [45, 45], [55, 55] ] }).to_a # [lower_left, top_right]
20
+
21
+ N.B. bounds queries are syntactically ugly at the moment and are likely to change soon
22
+
23
+ ### geoNear and convenience methods
24
+ nearby = TestAsset.near([50, 50], :num => 15, :query => { ... })
25
+ nearby.average_distance # average distance of all results from the target point
26
+ nearby.first.distance # distance of this result from the target
27
+ TestAsset.first.distance_from([50, 50]) # distance from any point
28
+ Queries can be specified with the [ruby driver style finders](http://github.com/mongodb/mongo-ruby-driver/blob/master/examples/queries.rb)
29
+
30
+ ## Note on Patches/Pull Requests
31
+
32
+ * Fork the project.
33
+ * Make your feature addition or bug fix.
34
+ * Add tests for it. This is important so I don't break it in a
35
+ future version unintentionally.
36
+ * Commit, do not mess with rakefile, version, or history.
37
+ (if you want to have your own version, that is fine but bump version in a commit by itself I can ignore when I pull)
38
+ * Send me a pull request. Bonus points for topic branches.
data/Rakefile ADDED
@@ -0,0 +1,53 @@
1
+ require 'rubygems'
2
+ require 'rake'
3
+
4
+ begin
5
+ require 'jeweler'
6
+ Jeweler::Tasks.new do |gem|
7
+ gem.name = "mongo_geo"
8
+ gem.summary = %Q{A MongoMapper plugin that adds geospatial functionality.}
9
+ gem.description = %Q{A MongoMapper plugin that adds geospatial functionality.}
10
+ gem.email = "mtparrish@gmail.com"
11
+ gem.homepage = "http://github.com/parrish/mongo_geo"
12
+ gem.authors = ["Michael Parrish"]
13
+ gem.add_development_dependency "thoughtbot-shoulda", ">= 0"
14
+ gem.add_dependency "mongo_mapper", ">= 0.8.2"
15
+ end
16
+ Jeweler::GemcutterTasks.new
17
+ rescue LoadError
18
+ puts "Jeweler (or a dependency) not available. Install it with: gem install jeweler"
19
+ end
20
+
21
+ require 'rake/testtask'
22
+ Rake::TestTask.new(:test) do |test|
23
+ test.libs << 'lib' << 'test'
24
+ test.pattern = 'test/**/test_*.rb'
25
+ test.verbose = true
26
+ end
27
+
28
+ begin
29
+ require 'rcov/rcovtask'
30
+ Rcov::RcovTask.new do |test|
31
+ test.libs << 'test'
32
+ test.pattern = 'test/**/test_*.rb'
33
+ test.verbose = true
34
+ end
35
+ rescue LoadError
36
+ task :rcov do
37
+ abort "RCov is not available. In order to run rcov, you must: sudo gem install spicycode-rcov"
38
+ end
39
+ end
40
+
41
+ task :test => :check_dependencies
42
+
43
+ task :default => :test
44
+
45
+ require 'rake/rdoctask'
46
+ Rake::RDocTask.new do |rdoc|
47
+ version = File.exist?('VERSION') ? File.read('VERSION') : ""
48
+
49
+ rdoc.rdoc_dir = 'rdoc'
50
+ rdoc.title = "mongo_geo #{version}"
51
+ rdoc.rdoc_files.include('README*')
52
+ rdoc.rdoc_files.include('lib/**/*.rb')
53
+ end
data/VERSION ADDED
@@ -0,0 +1 @@
1
+ 0.1.0
data/lib/mongo_geo.rb ADDED
@@ -0,0 +1,81 @@
1
+ require 'mongo_mapper'
2
+
3
+ module Plucky
4
+ module Extensions
5
+ module Symbol
6
+ def near
7
+ SymbolOperator.new(self, 'near')
8
+ end
9
+
10
+ def within
11
+ SymbolOperator.new(self, 'within')
12
+ end
13
+ end
14
+ end
15
+ end
16
+
17
+ module GeoSpatial
18
+ module ClassMethods
19
+ def geo_key(name, klass)
20
+ unless [Array, Hash].include?(klass)
21
+ raise(ArgumentError, "#{klass} is not a valid type for a geo_key\nUse either an Array(recommended) or a Hash")
22
+ end
23
+
24
+ if @geo_key_name.nil?
25
+ key name.to_sym, klass
26
+ ensure_index([[name, Mongo::GEO2D]])
27
+ @geo_key_name = name
28
+ else
29
+ error = "MongoDB is currently limited to only one geospatial index per collection.\n"
30
+ error += "geo_key #{name} was NOT added to #{self.name}"
31
+ raise(RuntimeError, error)
32
+ end
33
+ end
34
+
35
+ def geo_key_name
36
+ @geo_key_name
37
+ end
38
+
39
+ def near(location, params = {})
40
+ args = BSON::OrderedHash.new
41
+ args[:geoNear] = self.collection.name
42
+ args[:near] = location
43
+ params.each_pair{ |key, value| args[key.to_sym] = value }
44
+
45
+ raw = database.command(args)
46
+ objects = raw["results"].collect{ |r| self.load(r["obj"]) }
47
+ objects.instance_variable_set(:@raw, raw)
48
+
49
+ objects.each.with_index do |obj, index|
50
+ obj.instance_variable_set(:@distance, raw["results"][index]["dis"])
51
+ def obj.distance
52
+ @distance
53
+ end
54
+ end
55
+
56
+ def objects.average_distance
57
+ @raw["stats"]["avgDistance"]
58
+ end
59
+
60
+ objects
61
+ end
62
+ end
63
+
64
+ module InstanceMethods
65
+ def distance_from(pt)
66
+ name = self.class.geo_key_name
67
+ return nil if name.nil?
68
+ raise(ArgumentError) unless [Array, Hash].include?(pt.class)
69
+
70
+ loc = self.send(name)
71
+ loc = loc.values if loc.is_a?(Hash)
72
+ pt = pt.values if pt.is_a?(Hash)
73
+
74
+ dx = loc[0] - pt[0]
75
+ dy = loc[1] - pt[1]
76
+ Math.sqrt((dx ** 2) + (dy ** 2))
77
+ end
78
+ end
79
+ end
80
+
81
+ MongoMapper::Plugins.send :include, GeoSpatial
data/mongo_geo.gemspec ADDED
@@ -0,0 +1,59 @@
1
+ # Generated by jeweler
2
+ # DO NOT EDIT THIS FILE DIRECTLY
3
+ # Instead, edit Jeweler::Tasks in Rakefile, and run the gemspec command
4
+ # -*- encoding: utf-8 -*-
5
+
6
+ Gem::Specification.new do |s|
7
+ s.name = %q{mongo_geo}
8
+ s.version = "0.1.0"
9
+
10
+ s.required_rubygems_version = Gem::Requirement.new(">= 0") if s.respond_to? :required_rubygems_version=
11
+ s.authors = ["Michael Parrish"]
12
+ s.date = %q{2010-07-19}
13
+ s.description = %q{A MongoMapper plugin that adds geospatial functionality.}
14
+ s.email = %q{mtparrish@gmail.com}
15
+ s.extra_rdoc_files = [
16
+ "LICENSE",
17
+ "README.markdown"
18
+ ]
19
+ s.files = [
20
+ ".document",
21
+ ".gitignore",
22
+ "LICENSE",
23
+ "README.markdown",
24
+ "Rakefile",
25
+ "VERSION",
26
+ "lib/mongo_geo.rb",
27
+ "mongo_geo.gemspec",
28
+ "test/helper.rb",
29
+ "test/test_mongo_geo.rb",
30
+ "test/test_plucky_extensions.rb"
31
+ ]
32
+ s.homepage = %q{http://github.com/parrish/mongo_geo}
33
+ s.rdoc_options = ["--charset=UTF-8"]
34
+ s.require_paths = ["lib"]
35
+ s.rubygems_version = %q{1.3.6}
36
+ s.summary = %q{A MongoMapper plugin that adds geospatial functionality.}
37
+ s.test_files = [
38
+ "test/helper.rb",
39
+ "test/test_mongo_geo.rb",
40
+ "test/test_plucky_extensions.rb"
41
+ ]
42
+
43
+ if s.respond_to? :specification_version then
44
+ current_version = Gem::Specification::CURRENT_SPECIFICATION_VERSION
45
+ s.specification_version = 3
46
+
47
+ if Gem::Version.new(Gem::RubyGemsVersion) >= Gem::Version.new('1.2.0') then
48
+ s.add_development_dependency(%q<thoughtbot-shoulda>, [">= 0"])
49
+ s.add_runtime_dependency(%q<mongo_mapper>, [">= 0.8.2"])
50
+ else
51
+ s.add_dependency(%q<thoughtbot-shoulda>, [">= 0"])
52
+ s.add_dependency(%q<mongo_mapper>, [">= 0.8.2"])
53
+ end
54
+ else
55
+ s.add_dependency(%q<thoughtbot-shoulda>, [">= 0"])
56
+ s.add_dependency(%q<mongo_mapper>, [">= 0.8.2"])
57
+ end
58
+ end
59
+
data/test/helper.rb ADDED
@@ -0,0 +1,25 @@
1
+ require 'rubygems'
2
+ require 'test/unit'
3
+ require 'shoulda'
4
+ require 'mongo_mapper'
5
+
6
+ $LOAD_PATH.unshift(File.join(File.dirname(__FILE__), '..', 'lib'))
7
+ $LOAD_PATH.unshift(File.dirname(__FILE__))
8
+ require 'mongo_geo'
9
+
10
+ connection = Mongo::Connection.new('127.0.0.1', 27017)
11
+ DB = connection.db('mongo-geo')
12
+ MongoMapper.database = "mongo-geo"
13
+
14
+ class TestAsset
15
+ include MongoMapper::Document
16
+ plugin GeoSpatial
17
+
18
+ geo_key :coords, Array
19
+ end
20
+
21
+ class Test::Unit::TestCase
22
+ def setup
23
+ DB['assets'].remove
24
+ end
25
+ end
@@ -0,0 +1,53 @@
1
+ require 'helper'
2
+
3
+ class TestMongoGeo < Test::Unit::TestCase
4
+ context "Initializing a model" do
5
+ setup do
6
+ @asset1 = TestAsset.create(:coords => [50, 50])
7
+ @asset2 = TestAsset.create(:coords => [60, 60])
8
+ @asset3 = TestAsset.create(:coords => [70, 70])
9
+ end
10
+
11
+ should "create the 2d index" do
12
+ assert_equal(TestAsset.geo_key_name, :coords)
13
+ assert(TestAsset.collection.index_information['coords_2d'], "geo_key did not define the 2d index")
14
+ end
15
+
16
+ should "validate #geo_key type" do
17
+ assert_raise(ArgumentError) { TestAsset.geo_key(:blah, Float) }
18
+ assert_raise(RuntimeError) { TestAsset.geo_key(:no_more, Array) }
19
+ end
20
+
21
+ should "allow plucky queries using #near" do
22
+ nearby = TestAsset.where(:coords.near => [45, 45]).to_a
23
+ assert_equal(nearby.first, @asset1)
24
+ assert_equal(nearby.last, @asset3)
25
+ end
26
+
27
+ should "allow plucky queries using #within" do
28
+ nearby = TestAsset.where(:coords.within => { "$center" => [[45, 45], 10] }).to_a
29
+ assert_equal(nearby, [@asset1])
30
+ end
31
+
32
+ should "allow geoNear style queries with #near" do
33
+ nearby = TestAsset.near([45, 45], :num => 2)
34
+ assert_equal(2, nearby.count)
35
+ assert_equal(@asset1, nearby.first)
36
+
37
+ assert(nearby.methods.include?(:average_distance), "#near did not define average_distance")
38
+ assert_equal(nearby.average_distance.class, Float)
39
+
40
+ assert(nearby.first.methods.include?(:distance), "#near did not define distance on each record")
41
+ assert_equal(nearby.first.distance.class, Float)
42
+ end
43
+
44
+ should "perform a simple #distance_from calculation" do
45
+ assert(@asset1.methods.include?(:distance_from), "GeoSpatial::InstanceMethods were not included")
46
+ assert_equal(Math.sqrt(2), @asset1.distance_from([51, 51]))
47
+ assert_raise(ArgumentError) { @asset1.distance_from(51) }
48
+
49
+ TestAsset.collection.drop_indexes
50
+ TestAsset.collection.remove
51
+ end
52
+ end
53
+ end
@@ -0,0 +1,13 @@
1
+ require 'helper'
2
+
3
+ class TestMongoGeo < Test::Unit::TestCase
4
+ context "Extending Plucky symbols" do
5
+ should "add #near" do
6
+ assert Plucky::Extensions::Symbol.instance_methods.include?(:near), "near symbol operator not created"
7
+ end
8
+
9
+ should "add #within" do
10
+ assert Plucky::Extensions::Symbol.instance_methods.include?(:within), "within symbol operator not created"
11
+ end
12
+ end
13
+ end
metadata ADDED
@@ -0,0 +1,100 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: mongo_geo
3
+ version: !ruby/object:Gem::Version
4
+ prerelease: false
5
+ segments:
6
+ - 0
7
+ - 1
8
+ - 0
9
+ version: 0.1.0
10
+ platform: ruby
11
+ authors:
12
+ - Michael Parrish
13
+ autorequire:
14
+ bindir: bin
15
+ cert_chain: []
16
+
17
+ date: 2010-07-19 00:00:00 -05:00
18
+ default_executable:
19
+ dependencies:
20
+ - !ruby/object:Gem::Dependency
21
+ name: thoughtbot-shoulda
22
+ prerelease: false
23
+ requirement: &id001 !ruby/object:Gem::Requirement
24
+ requirements:
25
+ - - ">="
26
+ - !ruby/object:Gem::Version
27
+ segments:
28
+ - 0
29
+ version: "0"
30
+ type: :development
31
+ version_requirements: *id001
32
+ - !ruby/object:Gem::Dependency
33
+ name: mongo_mapper
34
+ prerelease: false
35
+ requirement: &id002 !ruby/object:Gem::Requirement
36
+ requirements:
37
+ - - ">="
38
+ - !ruby/object:Gem::Version
39
+ segments:
40
+ - 0
41
+ - 8
42
+ - 2
43
+ version: 0.8.2
44
+ type: :runtime
45
+ version_requirements: *id002
46
+ description: A MongoMapper plugin that adds geospatial functionality.
47
+ email: mtparrish@gmail.com
48
+ executables: []
49
+
50
+ extensions: []
51
+
52
+ extra_rdoc_files:
53
+ - LICENSE
54
+ - README.markdown
55
+ files:
56
+ - .document
57
+ - .gitignore
58
+ - LICENSE
59
+ - README.markdown
60
+ - Rakefile
61
+ - VERSION
62
+ - lib/mongo_geo.rb
63
+ - mongo_geo.gemspec
64
+ - test/helper.rb
65
+ - test/test_mongo_geo.rb
66
+ - test/test_plucky_extensions.rb
67
+ has_rdoc: true
68
+ homepage: http://github.com/parrish/mongo_geo
69
+ licenses: []
70
+
71
+ post_install_message:
72
+ rdoc_options:
73
+ - --charset=UTF-8
74
+ require_paths:
75
+ - lib
76
+ required_ruby_version: !ruby/object:Gem::Requirement
77
+ requirements:
78
+ - - ">="
79
+ - !ruby/object:Gem::Version
80
+ segments:
81
+ - 0
82
+ version: "0"
83
+ required_rubygems_version: !ruby/object:Gem::Requirement
84
+ requirements:
85
+ - - ">="
86
+ - !ruby/object:Gem::Version
87
+ segments:
88
+ - 0
89
+ version: "0"
90
+ requirements: []
91
+
92
+ rubyforge_project:
93
+ rubygems_version: 1.3.6
94
+ signing_key:
95
+ specification_version: 3
96
+ summary: A MongoMapper plugin that adds geospatial functionality.
97
+ test_files:
98
+ - test/helper.rb
99
+ - test/test_mongo_geo.rb
100
+ - test/test_plucky_extensions.rb