Sha256: 12cc6f6f8f3754ffd9eb44b0f357bd7183e11e92ee52e60242b968b207151d36

Contents?: true

Size: 1.68 KB

Versions: 3

Compression:

Stored size: 1.68 KB

Contents

module AnsibleTowerClient
  class Collection
    attr_reader :api, :klass
    def initialize(api, klass = nil)
      @api   = api
      @klass = klass
    end

    # @param get_options [Hash] a hash of http GET params to pass to the api request
    #   e.g. { :order_by => 'timestamp', :name__contains => 'foo' }
    def all(get_options = nil)
      find_all_by_url(klass.endpoint, get_options)
    end

    def find_all_by_url(url, get_options = nil)
      Enumerator.new do |yielder|
        @collection = []
        next_page   = url

        loop do
          next_page = fetch_more_results(next_page, get_options) if @collection.empty?
          get_options = nil
          raise StopIteration if @collection.empty?
          yielder.yield(@collection.shift)
        end
      end
    end

    def find(id)
      build_object(parse_response(api.get("#{klass.endpoint}/#{id}/")))
    end

    def create!(*args)
      klass.create!(api, *args)
    end

    def create(*args)
      klass.create(api, *args)
    end

    private

    def class_from_type(type)
      api.send("#{type}_class")
    end

    def fetch_more_results(next_page, get_options)
      return if next_page.nil?
      body = parse_response(api.get(next_page, get_options))
      parse_result_set(body)
    end

    def parse_response(response)
      JSON.parse(response.body)
    end

    def parse_result_set(body)
      case body.class.name
      when "Array" then
        @collection = body
        nil
      when "Hash" then
        body["results"].each { |result| @collection << build_object(result) }
        body["next"]
      end
    end

    def build_object(result)
      class_from_type(result["type"]).new(api, result)
    end
  end
end

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
ansible_tower_client-0.8.0 lib/ansible_tower_client/collection.rb
ansible_tower_client-0.7.0 lib/ansible_tower_client/collection.rb
ansible_tower_client-0.6.0 lib/ansible_tower_client/collection.rb