module Sameas def self.new(options = nil) Sameas::Base.new(options) end class Base class_attr_accessor :http_open_timeout class_attr_accessor :http_read_timeout attr_accessor :api_endpoint @@http_open_timeout = 60 @@http_read_timeout = 60 API_ENDPOINT = 'http://www.sameas.org/json' # create a new sameas object # def initialize(config_hash_or_file) return if config_hash_or_file.nil? if config_hash_or_file.is_a? Hash config_hash_or_file.nested_symbolize_keys! @api_endpoint = config_hash_or_file[:api_endpoint] else config = YAML.load_file(config_hash_or_file) config.nested_symbolize_keys! @api_endpoint = config[:api_endpoint] end end # sends a request to the sameas api # # Params # * api_url (Required) # the request url (uri.path) # * http_method (Optional) # choose between GET (default), POST, PUT, DELETE http request. # * options (Optional) # hash of query parameters # def send_request(api_url, http_method = :get, options= {}) raise 'no api_url supplied' unless api_url res = request_over_http(api_url, http_method, options) # Strip any js wrapping methods #puts res.body if res.body =~ /^.+\((.+)\)$/ r = JSON.parse($1) else r = JSON.parse(res.body) end return r end def find(identifier, typeof) raise "no identifier specified" if identifier.nil? raise "no type specified" if typeof.nil? case typeof when :uri api_url = "#{API_ENDPOINT}?uri=#{identifier}" when :term api_url = "#{API_ENDPOINT}?q=#{identifier}" else raise "Unknown type specified" end results = [] response = send_request(api_url, :get, {}) response.each do |result| results.push Sameas::Results.new(result) end case typeof when :uri return results.first when :term return results end end def find_by_uri(uri) find(uri, :uri) end def find_by_term(term) find(term, :term) end protected # For easier testing. You can mock this method with a XML file you re expecting to receive def request_over_http(api_url, http_method, options) req = nil http_opts = { "Accept" => "application/json", "User-Agent" => "sameasdotorg_fu" } url = URI.parse(api_url) case http_method when :get u = url.query.nil? ? url.path : url.path+"?"+url.query req = Net::HTTP::Get.new(u, http_opts) when :post req = Net::HTTP::Post.new(url.path, http_opts) when :put req = Net::HTTP::Put.new(url.path, http_opts) when :delete req = Net::HTTP::Delete.new(url.path, http_opts) else raise 'invalid http method specified' end req.set_form_data(options) unless options.keys.empty? #req.basic_auth @username, @password http = Net::HTTP.new(url.host, url.port) http.open_timeout = @@http_open_timeout http.read_timeout = @@http_read_timeout http.start do |http| res = http.request(req) case res when Net::HTTPSuccess return res else raise Sameas::Errors.error_for(res.code, 'HTTP Error') end end end end end