lib/redbooth-ruby/request/collection.rb in redbooth-ruby-0.0.4 vs lib/redbooth-ruby/request/collection.rb in redbooth-ruby-0.0.5

- old
+ new

@@ -13,15 +13,11 @@ # Returns an array of resuce objects built from each one of the response items # # @return [Array(resource)] def all - results = [] - response.data.each do |obj| - results << resource.new(obj) - end - results + results_from(response) end # Returns total pages # # @return [Integer] @@ -72,9 +68,45 @@ return nil unless current_page > 1 request_with(page: current_page - 1) end protected + + # Returns the collection object build from the received response + # + # @param response [Array || Hash] parsed json response + # @return [RedboothRuby::Collection] + def results_from(response) + response.data.collect do |obj| + case resource + when RedboothRuby::Client + next unless resource_form_hash(obj.merge(session: session)) + resource_form_hash(obj.merge(session: session)) + else + resource.new(obj.merge(session: session)) + end + end.compact + end + + # Builds a resource ruby object based on the given hash + # it need to contain a 'type' key defining the object type + # + # @return [Redbooth::Base] + def resource_form_hash(hash) + return unless hash['type'] + klass_name = hash['type'] + klass = resource_klass(klass_name) + return unless klass + klass.new(hash) + end + + # Gest the api resource model class by his name + # + # @param [String||Symbol] name name of the resource + # @return [Copy::Base] resource to use the api + def resource_klass(name) + eval('RedboothRuby::' + name.to_s.capitalize) rescue nil + end # Whenever the response is paginated or not def paginated? return false unless current_page true