Sha256: 4c1df282af93657f0a075f454d25c8c61e23a926942e64f119471b6cb6e281c3

Contents?: true

Size: 1.48 KB

Versions: 38

Compression:

Stored size: 1.48 KB

Contents

module FbGraph
  class Collection < Array
    attr_reader :previous, :next, :total_count, :unread_count, :updated_time

    def initialize(collection = nil)
      collection = case collection
      when Array
        {:data => collection, :count => collection.size}
      when Hash
        collection[:data] ||= []
        collection
      when nil
        collection = {:data => [], :count => 0}
      else
        raise ArgumentError.new("Invalid collection")
      end

      # NOTE: Graph API returns {"data":{"to":[null]}} sometimes... :(
      collection[:data].delete_if(&:nil?)

      replace collection[:data]

      if (summary = collection[:summary]).present?
        @total_count = summary[:total_count]
        @unread_count = summary[:unread_count]
        @updated_time = Time.parse(summary[:updated_time]) if summary[:updated_time]
      else
        @total_count = collection[:count]
      end
      @previous, @next = {}, {}
      if (paging = collection[:paging])
        if paging[:previous]
          @previous = fetch_params(paging[:previous])
        end
        if paging[:next]
          @next = fetch_params(paging[:next])
        end
      end
    end

    private

    def fetch_params(url)
      query = URI.parse(URI.encode(url)).query
      params = {}
      query.split('&').each do |q|
        key, value = q.split('=')
        if ['limit', 'offset', 'until', 'since'].include?(key)
          params[key.to_sym] = URI.unescape(value)
        end
      end
      params
    end
  end
end

Version data entries

38 entries across 38 versions & 1 rubygems

Version Path
fb_graph-2.6.5 lib/fb_graph/collection.rb
fb_graph-2.6.4 lib/fb_graph/collection.rb
fb_graph-2.6.3 lib/fb_graph/collection.rb
fb_graph-2.6.2 lib/fb_graph/collection.rb
fb_graph-2.6.1 lib/fb_graph/collection.rb
fb_graph-2.6.0 lib/fb_graph/collection.rb
fb_graph-2.5.9 lib/fb_graph/collection.rb
fb_graph-2.5.8 lib/fb_graph/collection.rb
fb_graph-2.5.7 lib/fb_graph/collection.rb
fb_graph-2.5.6 lib/fb_graph/collection.rb
fb_graph-2.5.5 lib/fb_graph/collection.rb
fb_graph-2.5.4 lib/fb_graph/collection.rb
fb_graph-2.5.3 lib/fb_graph/collection.rb
fb_graph-2.5.2 lib/fb_graph/collection.rb
fb_graph-2.5.1 lib/fb_graph/collection.rb
fb_graph-2.5.0 lib/fb_graph/collection.rb
fb_graph-2.4.20 lib/fb_graph/collection.rb
fb_graph-2.4.19 lib/fb_graph/collection.rb
fb_graph-2.4.18 lib/fb_graph/collection.rb
fb_graph-2.4.17 lib/fb_graph/collection.rb