Sha256: 312ab111c070485b13c28449357f73f8a15e0433e67b53c89ca8c54c112c2100

Contents?: true

Size: 1.51 KB

Versions: 1

Compression:

Stored size: 1.51 KB

Contents

module LazyResource
  class ResourceQueue
    include LazyResource::UrlGeneration

    def initialize
      @queue = []
    end

    def queue(relation)
      @queue.push(relation)
    end

    def flush!
      @queue = []
    end

    def request_queue
      Thread.current[:request_queue] ||= Typhoeus::Hydra.new(:max_concurrency => LazyResource.max_concurrency)
    end

    def run
      send_to_request_queue!
      request_queue.run if request_queue.items_queued?
    end

    def send_to_request_queue!
      while(relation = @queue.pop)
        options = { :headers => relation.headers, :method => relation.method }

        if [:post, :put].include?(relation.method)
          options[:body] = relation.to_params.to_json
        end

        request = Request.new(url_for(relation), relation, options)
        request_queue.queue(request)
      end
    end

    def url_for(relation)
      if relation.route.nil?
        include_query = ![:post, :put].include?(relation.method)

        url = ''
        url << relation.klass.site
        url << relation.klass.collection_path(relation.to_params, nil, relation.from, include_query)
        url
      else
        url = relation.route
        url.gsub!(/:\w*/) do |match|
          attr = match[1..-1].to_sym
          if relation.where_values.has_key?(attr)
            relation.where_values[attr]
          else
            match
          end
        end

        if url =~ /http/
          url
        else
          relation.klass.site + url
        end
      end
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
lazy_resource-0.5.0 lib/lazy_resource/resource_queue.rb