lib/npr/api/query_builder.rb in npr-1.1.0 vs lib/npr/api/query_builder.rb in npr-1.2.0
- old
+ new
@@ -9,37 +9,37 @@
:order,
:limit,
:offset,
:set
]
-
+
attr_reader :_klass, :builder
#-----------------------
-
+
def initialize(klass)
@_klass = klass
@builder = {}
end
-
+
#-----------------------
# Build the params hash.
# This is automatically called by #to_a, so it probably
# doesn't need to be used manually.
def to_params
if @_klass == NPR::Entity::Story && @builder[:conditions]
conditions = parse_conditions(@builder[:conditions])
else
conditions = @builder[:conditions]
end
-
+
params = conditions || {}
params[:sort] = @builder[:order] if @builder[:order]
params[:numResults] = @builder[:limit] if @builder[:limit]
params[:startNum] = @builder[:offset] if @builder[:offset]
params.merge!(@builder[:extra]) if @builder[:extra]
-
+
params
end
#-----------------------
# Fire the query and return an Array of stories (or empty [])
@@ -66,23 +66,23 @@
# Note that for this method, +NPR.config.apiKey+ must be set.
#
def to_a
response = self.query
stories = []
-
+
if response.list
stories = Array.wrap(response.list.stories)
end
-
+
stories
end
-
+
#-----------------------
# Fire the query and return the full Response object
- #
+ #
# Example:
- #
+ #
# query = NPR::API::QueryBuilder.new(NPR::Story)
# query.where(:id => [100, 150]).query
# #=> NPR::API::Response
#
# See NPR::API::Response for what methods are available
@@ -108,11 +108,11 @@
#
def set(params)
@builder[:extra] = (@builder[:extra] || {}).merge(params)
self
end
-
+
#-----------------------
# Merge in the passed-in conditions to what
# already exists.
#
# Accepts a Hash.
@@ -130,11 +130,11 @@
# * You may pass a date range to :date
#
# last_week = Time.new(2012, 10, 21)
# yesterday = Time.new(2012, 10, 25)
# query.where(date: (last_week..yesterday))
- #
+ #
def where(conditions)
@builder[:conditions] = (@builder[:conditions] || {}).merge(conditions)
self
end
@@ -166,13 +166,13 @@
# maximum is requested.
def limit(limit)
@builder[:limit] = limit
self
end
-
+
#-----------------------
- # Offset the number of results
+ # Offset the number of results
# Useful for pagination
#
# Accepts an Integer.
#
# Example:
@@ -181,38 +181,37 @@
#
def offset(offset)
@builder[:offset] = offset
self
end
-
+
#-----------------------
-
+
private
-
+
def client
@client ||= NPR::API::Client.new(:apiKey => NPR.config.apiKey)
end
-
+
#-----------------------
-
+
def parse_conditions(conditions)
parse_conditions!(conditions.dup)
end
#-----------------------
-
+
def parse_conditions!(conditions)
-
if conditions[:id].is_a? Array
conditions[:id] = conditions[:id].join(",")
end
-
+
if conditions[:date].is_a? Range
conditions[:startDate] = conditions[:date].first
conditions[:endDate] = conditions[:date].last
conditions.delete(:date)
end
-
+
conditions
end
end # QueryBuilder
end # API
end # NPR