lib/ably/models/paginated_resource.rb in ably-0.7.0 vs lib/ably/models/paginated_resource.rb in ably-0.7.1

- old
+ new

@@ -3,11 +3,11 @@ # the array of resources using {#first_page}, {#next_page}, {#first_page?} and {#last_page?} # # Paging information is provided by Ably in the LINK HTTP headers class PaginatedResource include Enumerable - include Ably::Modules::AsyncWrapper if defined?(EventMachine) + include Ably::Modules::AsyncWrapper if defined?(Ably::Realtime) # @param [Faraday::Response] http_response Initial HTTP response from an Ably request to a paged resource # @param [String] base_url Base URL for request that generated the http_response so that subsequent paged requests can be made # @param [Client] client {Ably::Client} used to make the request to Ably # @param [Hash] options Options for this paged resource @@ -23,23 +23,13 @@ @coerce_into = options[:coerce_into] @raw_body = http_response.body @each_block = each_block @make_async = options.fetch(:async_blocking_operations, false) - @body = if @coerce_into - http_response.body.map do |item| - @coerce_into.split('::').inject(Kernel) do |base, klass_name| - base.public_send(:const_get, klass_name) - end.new(item) - end - else - http_response.body - end - - @body = @body.map do |resource| - each_block.call(resource) - end if block_given? + @body = http_response.body + @body = coerce_items_into(body, @coerce_into) if @coerce_into + @body = body.map { |item| yield item } if block_given? end # Retrieve the first page of results. # When used as part of the {Ably::Realtime} library, it will return a {EventMachine::Deferrable} object, # and allows an optional success callback block to be provided. @@ -98,17 +88,12 @@ alias_method :count, :length alias_method :size, :length # Method to allow {PaginatedResource} to be {http://ruby-doc.org/core-2.1.3/Enumerable.html Enumerable} def each(&block) - body.each do |item| - if block_given? - block.call item - else - yield item - end - end + return to_enum(:each) unless block_given? + body.each(&block) end # First item in this page def first body.first @@ -131,9 +116,17 @@ EOF end private attr_reader :body, :http_response, :base_url, :client, :coerce_into, :raw_body, :each_block, :make_async + + def coerce_items_into(items, type_string) + items.map do |item| + @coerce_into.split('::').inject(Kernel) do |base, klass_name| + base.public_send(:const_get, klass_name) + end.new(item) + end + end def pagination_headers link_regex = %r{<(?<url>[^>]+)>; rel="(?<rel>[^"]+)"} @pagination_headers ||= begin # All `Link:` headers are concatenated by Faraday into a comma separated list