lib/hungry/collection.rb in hungry-0.0.1 vs lib/hungry/collection.rb in hungry-0.1.0
- old
+ new
@@ -1,7 +1,6 @@
-require 'httparty'
-require 'cgi'
+require 'httparty' unless defined? HTTParty
module Hungry
class Collection
include Enumerable
include HTTParty
@@ -11,11 +10,10 @@
attr_reader :klass, :endpoint, :criteria
### CLASS METHODS:
def self.get(*args)
- puts "[Collection]: GET #{args.map(&:inspect).join(', ')}"
self.base_uri Hungry.api_url
super
end
### INSTANCE METHODS:
@@ -35,31 +33,67 @@
def all(new_criteria = {})
self.class.new(klass, endpoint, criteria.merge(new_criteria))
end
+ def [](index)
+ build_resource results[index]
+ end
+
+ def first(n = 1)
+ if n == 1 && (value = results.first)
+ build_resource value
+ elsif n > 1
+ results.first(n).map do |result|
+ build_resource result
+ end
+ end
+ end
+
def count(*args)
if args.present?
super
else
- response['results'].count
+ results.count
end
end
def each(&block)
- response['results'].each do |result|
- yield klass.new(result)
+ results.each do |result|
+ yield build_resource(result)
end
end
- private
+ def results
+ @results ||= json['results']
+ end
+ def results=(results)
+ @results = results
+ end
+
+ protected
+
+ def build_resource(result)
+ resource = klass.new(result)
+ resource.data_source = data_source
+ resource
+ end
+
+ def data_source
+ Util.uri_with_params(endpoint, criteria)
+ end
+
+ def json
+ @json ||= Util.parse_json(response.body)
+ end
+
def response
raise NoEndpointSpecified unless endpoint
@response ||= begin
- uri = Util.uri_with_params(endpoint, criteria)
- self.class.get uri
+ Util.log "GET: #{data_source}"
+ self.class.get data_source
end
end
end
end