Sha256: 17d3206cee08258a7e3d406915b7e206bb9525211c91592c7702b4378addf006

Contents?: true

Size: 1.36 KB

Versions: 34

Compression:

Stored size: 1.36 KB

Contents

module FbGraph2
  class Collection < Array
    attr_accessor :before, :after, :next, :previous, :total_count, :summary

    def initialize(collection = [])
      collection = normalize collection
      paginate collection[:paging]
      summarize collection[:summary]
      replace Array(collection[:data])
    end

    private

    def normalize(collection)
      case collection
      when Hash
        collection
      when Array
        {
          data:  collection,
          count: collection.size
        }
      else
        raise ArgumentError.new("Invalid collection")
      end
    end

    def paginate(paging)
      cursors  = paging.try(:[], :cursors)
      self.before   = cursors.try(:[], :before)
      self.after    = cursors.try(:[], :after)
      self.next     = params_in paging.try(:[], :next)
      self.previous = params_in paging.try(:[], :previous)
    end

    def summarize(summary)
      self.summary     = summary
      self.total_count = summary.try(:[], :total_count)
      if summary.try(:[], :updated_time)
        self.summary[:updated_time] = Time.parse summary[:updated_time]
      end
    end

    def params_in(url)
      if url
        Rack::Utils.parse_nested_query(
          URI.parse(url).query
        ).inject({}) do |params, (key, value)|
          params.merge! key => value
        end.with_indifferent_access
      end
    end
  end
end

Version data entries

34 entries across 34 versions & 1 rubygems

Version Path
fb_graph2-1.3.0 lib/fb_graph2/collection.rb
fb_graph2-1.2.0 lib/fb_graph2/collection.rb
fb_graph2-1.1.1 lib/fb_graph2/collection.rb
fb_graph2-1.1.0 lib/fb_graph2/collection.rb
fb_graph2-1.0.1 lib/fb_graph2/collection.rb
fb_graph2-1.0.0 lib/fb_graph2/collection.rb
fb_graph2-0.9.1 lib/fb_graph2/collection.rb
fb_graph2-0.9.0 lib/fb_graph2/collection.rb
fb_graph2-0.8.0 lib/fb_graph2/collection.rb
fb_graph2-0.7.9 lib/fb_graph2/collection.rb
fb_graph2-0.7.8 lib/fb_graph2/collection.rb
fb_graph2-0.7.7 lib/fb_graph2/collection.rb
fb_graph2-0.7.6 lib/fb_graph2/collection.rb
fb_graph2-0.7.5 lib/fb_graph2/collection.rb
fb_graph2-0.7.4 lib/fb_graph2/collection.rb
fb_graph2-0.7.3 lib/fb_graph2/collection.rb
fb_graph2-0.7.2 lib/fb_graph2/collection.rb
fb_graph2-0.7.1 lib/fb_graph2/collection.rb
fb_graph2-0.7.0 lib/fb_graph2/collection.rb
fb_graph2-0.6.2 lib/fb_graph2/collection.rb