Sha256: 28d6fcfe4e2f9691e4979f2757809840d77bcc7d079ebc7d923f8b3d4d32757f

Contents?: true

Size: 1.89 KB

Versions: 1

Compression:

Stored size: 1.89 KB

Contents

require 'geocoder'
require 'json'
require 'net/http'

module LocationOne
  #SUPPORTED_BACKENDS =
  #    {
  #        :calabashios => {:path => "/uia"},
  #        :calabashandroid => {:path => "/uia"},
  #        :frank => {:path => "/tbd"},
  #
  #    }

  class Client
    attr_accessor :http, :backend

    def initialize(backend,opt_client=nil)
      @backend = backend
      @http = opt_client || Net::HTTP.new(backend[:host], backend[:port])
    end

    def change_location(options, opt_data={})

      if (options[:latitude] and not options[:longitude]) or
          (options[:longitude] and not options[:latitude])
        raise "Both latitude and longitude must be specified if either is."
      end
      if (options[:latitude])
        change_location_by_coords(options[:latitude], options[:longitude],opt_data)
      else
        if not options[:place]
          raise "Either :place or :latitude and :longitude must be specified."
        end
        change_location_by_place(options[:place],opt_data)
      end
    end

    def change_location_by_coords(lat, lon,opt_data={})
      req = Net::HTTP::Post.new(backend[:path])

      body_data = {:action => :change_location,
                   :latitude => lat,
                   :longitude => lon}.merge(opt_data)

      req.body = body_data.to_json

      res = @http.request(req)

      begin
        @http.finish if @http.started?
      rescue

      end
      if res.code !='200'
        raise "Response error code #{res.code}, for #{lat}, #{lon} (#{res.body})."
      end
      res.body
    end

    def self.location_by_place(place)
      results = Geocoder.search(place)
      raise "Got no results for #{place}" if results.empty?
      results.first
    end

    def change_location_by_place(place,opt_data={})
      best_result = location_by_place(place)
      change_location_by_coords(best_result.latitude, best_result.longitude,opt_data)
    end

  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
location-one-0.0.2 lib/location-one/core.rb