Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Browse files

Initial commit

  • Loading branch information...
commit a828f083c14e7832e6cae22ba9fffeac31c28d81 0 parents
@archfear archfear authored
5 .document
@@ -0,0 +1,5 @@
+README.rdoc
+lib/**/*.rb
+bin/*
+features/**/*.feature
+LICENSE
21 .gitignore
@@ -0,0 +1,21 @@
+## MAC OS
+.DS_Store
+
+## TEXTMATE
+*.tmproj
+tmtags
+
+## EMACS
+*~
+\#*
+.\#*
+
+## VIM
+*.swp
+
+## PROJECT::GENERAL
+coverage
+rdoc
+pkg
+
+## PROJECT::SPECIFIC
20 LICENSE
@@ -0,0 +1,20 @@
+Copyright (c) 2009 Dan Dofter
+
+Permission is hereby granted, free of charge, to any person obtaining
+a copy of this software and associated documentation files (the
+"Software"), to deal in the Software without restriction, including
+without limitation the rights to use, copy, modify, merge, publish,
+distribute, sublicense, and/or sell copies of the Software, and to
+permit persons to whom the Software is furnished to do so, subject to
+the following conditions:
+
+The above copyright notice and this permission notice shall be
+included in all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
17 README.rdoc
@@ -0,0 +1,17 @@
+= sg-ruby
+
+Description goes here.
+
+== Note on Patches/Pull Requests
+
+* Fork the project.
+* Make your feature addition or bug fix.
+* Add tests for it. This is important so I don't break it in a
+ future version unintentionally.
+* Commit, do not mess with rakefile, version, or history.
+ (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)
+* Send me a pull request. Bonus points for topic branches.
+
+== Copyright
+
+Copyright (c) 2010 Dan Dofter. See LICENSE for details.
60 Rakefile
@@ -0,0 +1,60 @@
+require 'rubygems'
+require 'rake'
+
+begin
+ require 'jeweler'
+ Jeweler::Tasks.new do |gem|
+ gem.name = "sg-ruby"
+ gem.summary = %Q{A SimpleGeo Ruby Client}
+ # gem.description = %Q{}
+ gem.email = "dan@dofter.com"
+ gem.homepage = "http://github.com/archfear/sg-ruby"
+ gem.authors = ["Dan Dofter"]
+
+ gem.add_dependency("oauth", ">= 0.4.0")
+ gem.add_dependency("json_pure", "~> 1.2.4")
+
+ gem.add_development_dependency("shoulda", "~> 2.10.0")
+ gem.add_development_dependency("jnunemaker-matchy", "~> 0.4.0")
+ gem.add_development_dependency("mocha", "~> 0.9.0")
+ gem.add_development_dependency("fakeweb", "~> 1.2.0")
+ # gem is a Gem::Specification... see http://www.rubygems.org/read/chapter/20 for additional settings
+ end
+ Jeweler::GemcutterTasks.new
+rescue LoadError
+ puts "Jeweler (or a dependency) not available. Install it with: gem install jeweler"
+end
+
+require 'rake/testtask'
+Rake::TestTask.new(:test) do |test|
+ test.libs << 'lib' << 'test'
+ test.pattern = 'test/**/*_test.rb'
+ test.verbose = true
+end
+
+begin
+ require 'rcov/rcovtask'
+ Rcov::RcovTask.new do |test|
+ test.libs << 'test'
+ test.pattern = 'test/**/*_test.rb'
+ test.verbose = true
+ end
+rescue LoadError
+ task :rcov do
+ abort "RCov is not available. In order to run rcov, you must: sudo gem install spicycode-rcov"
+ end
+end
+
+task :test => :check_dependencies
+
+task :default => :test
+
+require 'rake/rdoctask'
+Rake::RDocTask.new do |rdoc|
+ version = File.exist?('VERSION') ? File.read('VERSION') : ""
+
+ rdoc.rdoc_dir = 'rdoc'
+ rdoc.title = "sg-ruby #{version}"
+ rdoc.rdoc_files.include('README*')
+ rdoc.rdoc_files.include('lib/**/*.rb')
+end
1  VERSION
@@ -0,0 +1 @@
+0.1.0
21 lib/simple_geo.rb
@@ -0,0 +1,21 @@
+require 'uri'
+require 'json'
+require 'oauth'
+
+require 'simple_geo/connection'
+require 'simple_geo/client'
+require 'simple_geo/record'
+
+module SimpleGeo
+ API_VERSION = '0.1'.freeze
+ REALM = "http://api.simplegeo.com"
+ VERSION = File.read(File.join(File.dirname(__FILE__), '..', 'VERSION'))
+
+ class SimpleGeoError < StandardError; end
+ class Unauthorized < SimpleGeoError; end
+ class NotFound < SimpleGeoError; end
+ class ServerError < SimpleGeoError; end
+ class Unavailable < SimpleGeoError; end
+ class DecodeError < SimpleGeoError; end
+ class NoConnectionEstablished < SimpleGeoError; end
+end
167 lib/simple_geo/client.rb
@@ -0,0 +1,167 @@
+module SimpleGeo
+
+ class Endpoint
+
+ class << self
+ def record(layer, id)
+ endpoint_url "records/#{layer}/#{id}.json"
+ end
+
+ def records(layer, ids)
+ ids = ids.join(',') if ids.is_a? Array
+ endpoint_url "records/#{layer}/#{ids}.json"
+ end
+
+ def add_records(layer)
+ endpoint_url "records/#{layer}.json"
+ end
+
+ def history(layer, id)
+ endpoint_url "records/#{layer}/#{id}/history.json"
+ end
+
+ def nearby(layer, geohash)
+ endpoint_url "records/#{layer}/nearby/#{geohash}.json"
+ end
+
+ def nearby_address(lat, lon)
+ endpoint_url "nearby/address/#{lat},#{lon}.json"
+ end
+
+ def density(lat, lon, day, hour=nil)
+ if hour.nil?
+ path = "density/#{day}/#{lat},#{lon}.json"
+ else
+ path = "density/#{day}/#{hour}/#{lat},#{lon}.json"
+ end
+ endpoint_url path
+ end
+
+ def layer(layer)
+ endpoint_url "layer/#{layer}.json"
+ end
+
+ def contains(lat, lon)
+ endpoint_url "contains/#{lat},#{lon}.json"
+ end
+
+ def overlaps(south, west, north, east)
+ endpoint_url "overlaps/#{south},#{west},#{north},#{east}.json"
+ end
+
+ def boundary(id)
+ endpoint_url "boundary/#{id}.json"
+ end
+
+ def endpoint_url(path)
+ [REALM, API_VERSION, path].join('/')
+ end
+ end
+
+ end
+
+ class Client
+
+ @@connection = nil
+ @@debug = false
+
+ class << self
+
+ def set_credentials(token, secret)
+ @@connection = Connection.new(token, secret)
+ @@connection.debug = @@debug
+ end
+
+ def debug=(debug_flag)
+ @@debug = debug_flag
+ @@connection.debug = @@debug if @@connection
+ end
+
+ def debug
+ @@debug
+ end
+
+ def add_record(record)
+ raise SimpleGeoError, "Record has no layer" if record.layer.nil?
+ put Endpoint.record(record.layer, record.id), record
+ end
+
+ def delete_record(layer, id)
+ delete Endpoint.record(layer, id)
+ end
+
+ def get_record(layer, id)
+ get Endpoint.record(layer, id)
+ end
+
+ def add_records(layer, records)
+ features = {
+ :type => 'FeatureCollection',
+ :features => records.collect { |record| record.to_hash }
+ }
+ post Endpoint.add_records(layer), "POST", features
+ end
+
+ def get_records(layer, ids)
+ features = get Endpoint.records(layer, ids)
+ features['features'] || []
+ end
+
+ def get_history(layer, id, options={})
+ get Endpoint.history(layer, id), options
+ end
+
+ #TODO: get nearby by lat, lon
+ # api.simplegeo.com/{version}/records/{layer}/nearby/{lat},{lon}.json
+ def get_nearby(layer, geohash, options={})
+ get Endpoint.nearby(layer, geohash), options
+ end
+
+ def get_nearby_address(lat, lon)
+ get Endpoint.nearby_address(lat, lon)
+ end
+
+ def get_layer_information(layer)
+ get Endpoint.layer(layer)
+ end
+
+ def get_density(lat, lon, day, hour=nil)
+ get Endpoint.density(lat, lon, day, hour)
+ end
+
+ def get_overlaps(south, west, north, east, options)
+ get Endpoint.overlaps(south, west, north, east), options
+ end
+
+ def get_boundary(id)
+ get Endpoint.boundary(id)
+ end
+
+ def get_contains(lat, lon)
+ get Endpoint.contains(lat, lon)
+ end
+
+ def get(endpoint, data=nil)
+ raise NoConnectionEstablished if @@connection.nil?
+ @@connection.get endpoint, data
+ end
+
+ def delete(endpoint, data=nil)
+ raise NoConnectionEstablished if @@connection.nil?
+ @@connection.delete endpoint, data
+ end
+
+ def post(endpoint, data=nil)
+ raise NoConnectionEstablished if @@connection.nil?
+ @@connection.post endpoint, data
+ end
+
+ def put(endpoint, data=nil)
+ raise NoConnectionEstablished if @@connection.nil?
+ @@connection.put endpoint, data
+ end
+ end
+
+ end
+
+end
107 lib/simple_geo/connection.rb
@@ -0,0 +1,107 @@
+module SimpleGeo
+ class Connection
+
+ attr_accessor :debug
+
+ def initialize(token, secret)
+ consumer = OAuth::Consumer.new(token, secret, :site => REALM)
+ @access_token = OAuth::AccessToken.new(consumer)
+ debug = false
+ end
+
+ def get(endpoint, data=nil)
+ request :get, endpoint, data
+ end
+
+ def delete(endpoint, data=nil)
+ request :delete, endpoint, data
+ end
+
+ def post(endpoint, data=nil)
+ request :post, endpoint, data
+ end
+
+ def put(endpoint, data=nil)
+ request :put, endpoint, data
+ end
+
+ private
+
+ def request(method, endpoint, data)
+ data = data.to_json unless data.nil?
+
+ headers = {}
+ headers['User-Agent'] = "SimpleGeo Ruby Client v#{VERSION}"
+
+ if [:get, :delete].include?(method) && !data.nil?
+ endpoint = endpoint + '?' + build_query(data)
+ end
+
+ if debug
+ puts "request: #{method.to_s.upcase} #{endpoint}"
+ puts "headers:"
+ headers.each do |key, value|
+ puts "#{key}=#{value}"
+ end
+ end
+
+ case method
+ when :get, :delete
+ response = @access_token.request(method, endpoint, headers)
+ when :post, :put
+ response = @access_token.request(method, endpoint, data, headers)
+ end
+
+ if debug
+ puts "\nresponse:"
+ puts "headers:"
+ response.header.each do |key, value|
+ puts "#{key}=#{value}"
+ end
+ puts "body:"
+ puts response.body
+ end
+
+ raise_errors(response)
+
+ if response.body.empty?
+ content = nil
+ else
+ begin
+ content = JSON.parse(response.body)
+ rescue JSON::ParserError
+ raise DecodeError, "content: <#{response.body}>"
+ end
+ end
+
+ content
+ end
+
+ def build_query(data)
+ data.map do |key, value|
+ [key.to_s, URI.escape(value.to_s)].join('=')
+ end.join('&')
+ end
+
+ def raise_errors(response)
+ response_description = "(#{response.code}): #{response.message}"
+ response_description += " - #{response.body}" unless response.body.empty?
+
+ case response.code.to_i
+ when 401
+ raise Unauthorized
+ when 404
+ raise NotFound
+ when 500
+ raise ServerError, "SimpleGeo had an internal error. Please let them know. #{response_description}"
+ when 502..503
+ raise Unavailable, response_description
+ else
+ unless response.is_a? Net::HTTPSuccess
+ raise SimpleGeoError, response_description
+ end
+ end
+ end
+
+ end
+end
41 lib/simple_geo/record.rb
@@ -0,0 +1,41 @@
+module SimpleGeo
+ class Record
+
+ #TODO investigate whether to override id
+ attr_accessor :layer, :id, :lat, :lon, :type, :created, :properties
+
+ def initialize(options={})
+ options = {
+ :created => Time.now,
+ :type => 'object',
+ :properties => {}
+ }.merge(options)
+
+ layer = options[:layer]
+ id = options[:id]
+ lat = options[:lat]
+ lon = options[:lon]
+ type = options[:type]
+ created = options[:created]
+ properties = options[:properties]
+ end
+
+ def to_hash
+ {
+ :type => 'Feature',
+ :id => id,
+ :created => created,
+ :geometry => {
+ :type => 'Point',
+ :coordinates => [ body[:lon], body[:lat] ]
+ },
+ :properties => properties.join({:type => type})
+ }
+ end
+
+ def to_json
+ self.to_hash.to_json
+ end
+
+ end
+end
2  lib/simplegeo.rb
@@ -0,0 +1,2 @@
+# So you can require "simplegeo" instead of "simple_geo"
+require "simple_geo"
20 test/client_test.rb
@@ -0,0 +1,20 @@
+require 'test_helper'
+
+class ClientTest < Test::Unit::TestCase
+
+ context "performing a request for a single record" do
+ setup do
+ stub_request :get,
+ 'http://api.simplegeo.com/0.1/records/com.simplegeo.global.geonames/5373629.json',
+ :fixture_file => 'get_record.json'
+ SimpleGeo::Client.set_credentials 'token', 'secret'
+ SimpleGeo::Client.debug = true
+ @object = SimpleGeo::Client.get_record('com.simplegeo.global.geonames', 5373629)
+ end
+
+ should "return a single JSON object" do
+ @object.class.should be(Hash)
+ end
+ end
+
+end
38 test/fixtures/get_record.json
@@ -0,0 +1,38 @@
+{
+ "type": "Feature",
+ "id": "5373629",
+ "created": 1269832510,
+ "geometry": {
+ "type": "Point",
+ "coordinates": [
+ -122.42608,
+ 37.759650000000001
+ ]
+ },
+ "properties": {
+ "layer": "com.simplegeo.global.geonames",
+ "elevation": "22",
+ "gtopo30": "60",
+ "feature_code": "PRK",
+ "last_modified": "2006-01-15",
+ "country_code": "US",
+ "alternatenames": "",
+ "timezone": "America/Los_Angeles",
+ "population": "0",
+ "name": "Mission Dolores Park",
+ "feature_class": "L",
+ "cc2": "",
+ "admin1": "CA",
+ "admin3": "",
+ "admin2": "075",
+ "admin4": "",
+ "asciiname": "Mission Dolores Park",
+ "type": "place"
+ },
+ "layerLink": {
+ "href": "http://api.simplegeo.com/0.1/layer/com.simplegeo.global.geonames.json"
+ },
+ "selfLink": {
+ "href": "http://api.simplegeo.com/0.1/records/com.simplegeo.global.geonames/5373629.json"
+ }
+}
24 test/test_helper.rb
@@ -0,0 +1,24 @@
+require 'rubygems'
+require 'test/unit'
+require 'shoulda'
+require 'matchy'
+require 'fakeweb'
+
+$LOAD_PATH.unshift(File.join(File.dirname(__FILE__), '..', 'lib'))
+$LOAD_PATH.unshift(File.dirname(__FILE__))
+require 'simplegeo'
+
+class Test::Unit::TestCase
+end
+
+def fixture_file(filename)
+ file_path = File.expand_path(File.dirname(__FILE__) + "/fixtures/" + filename)
+ File.read(file_path)
+end
+
+def stub_request(method, url, options={})
+ if options[:fixture_file]
+ options[:body] = fixture_file(options.delete(:fixture_file))
+ end
+ FakeWeb.register_uri(method, url, options)
+end
Please sign in to comment.
Something went wrong with that request. Please try again.