Class: Collecta

Inherits:
Object
  • Object
show all
Defined in:
lib/collecta.rb

Constant Summary collapse

@@api_key =
nil
@@api_url =
"http://api.collecta.com/search"

Class Method Summary collapse

Class Method Details

.api_keyObject



14
15
16
# File 'lib/collecta.rb', line 14

def self.api_key
  @@api_key
end

.api_key=(key) ⇒ Object



18
19
20
# File 'lib/collecta.rb', line 18

def self.api_key=(key)
  @@api_key = key
end

.build_query(params, first = true) ⇒ Object



66
67
68
69
70
# File 'lib/collecta.rb', line 66

def self.build_query(params, first = true)
  query = (first) ? "?" : ""
  params[:format] = "json" if params[:format] == "hash"
  return query << params.map { |name, value| "#{name}=" + CGI::escape(value).gsub("+", "%20") }.join("&")
end

.build_url(params) ⇒ Object



45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
# File 'lib/collecta.rb', line 45

def self.build_url(params)
  if !params[:q].nil? && !params[:api_key].nil?
    # show specific categories
    if params[:category].is_a?(Array) && params[:category].size > 0
      params[:q] << params[:category].map { |item| " category:#{item}"}.join(" OR")
    elsif params[:category].is_a?(String)
      params[:q] << params[:category] && params[:category] != ""
    end
    params.delete(:category)
    # exclude specific categories
    if params[:exclude].is_a?(Array) && params[:exclude].size > 0
      params[:q] << params[:exclude].map { |item| " -category:#{item}"}.join(" OR")
    elsif params[:exclude].is_a?(String)
      params[:q] << params[:exclude] && params[:exclude] != ""
    end
    params.delete(:exclude)
    return @@api_url + self.build_query(params)
  end
  return false
end

.request(options = {}) ⇒ Object



30
31
32
33
34
35
36
37
38
39
40
41
42
43
# File 'lib/collecta.rb', line 30

def self.request(options = {})
  params = {}
  params[:api_key] = @@api_key if options[:api_key].nil?
  params[:format]  = (!options[:format].nil?) ? options[:format] : "atom"
  valid_params = [:q, :rpp, :page, :since_id, :callback, :category, :exclude]
  valid_params.each do |param|
    params[param] = options[param] if !options[param].nil?
  end
  request_url = self.build_url(params.clone)
  if request_url
    return Net::HTTP.get(URI.parse(request_url))
  end
  return false
end

.search(q = nil, params = {}) ⇒ Object



22
23
24
25
26
27
28
# File 'lib/collecta.rb', line 22

def self.search(q = nil, params = {})
  if !q.nil? && q != ""
    params[:q] = q
    return self.request(params)
  end
  return false
end