Sha256: 81bdac185808e453d4366c0035e54edb741d10691e10b80669f31063f14013de

Contents?: true

Size: 1.16 KB

Versions: 4

Compression:

Stored size: 1.16 KB

Contents

require 'net/http'
require 'uri'

module Cafepress
  module Search
    class Client
      attr_accessor :app_key

      def initialize(app_key)
        @app_key = app_key
      end

      def self.base_url
        @@base_url
      end

      def self.base_url=(url)
        @@base_url = url
      end

      def search(query, options = {})
        SearchResultSet.parse(Net::HTTP.get(query_url(options.merge('query' => query))))
      end

      private

      def query_url(options = {})
        URI.parse("#{Cafepress::Search::Client.base_url}/product.search.cp?#{format_options(options)}")
      end

      def format_options(options)
        options.merge('appKey' => app_key).collect do |key,value|
          "#{camelize(key)}=#{URI.escape(value)}"
        end.join('&')
      end

      # taken from rails/activesupport/lib/active_support/inflector.rb, line 178
      # Didn't want to require activesupport for one function
      def camelize(lower_case_and_underscored_word)
        camelized = lower_case_and_underscored_word.to_s.gsub(/\/(.?)/) { "::#{$1.upcase}" }.gsub(/(?:^|_)(.)/) { $1.upcase }
        camelized[0,1].downcase + camelized[1..-1]
      end
    end
  end
end

Version data entries

4 entries across 4 versions & 1 rubygems

Version Path
cafepress-search-1.1.0 lib/cafepress/search/client.rb
cafepress-search-1.0.2 lib/cafepress/search/client.rb
cafepress-search-1.0.1 lib/cafepress/search/client.rb
cafepress-search-1.0.0 lib/cafepress/search/client.rb