class TxTranslate::ParallelArray

Public Class Methods

new(array) click to toggle source

平行处理

# File lib/tx_translate/parallel_array.rb, line 14
def initialize(array)
  @content_array = array
  @result_array = []
  @hydra = Typhoeus::Hydra.new
end

Public Instance Methods

parallel_process() click to toggle source
# File lib/tx_translate/parallel_array.rb, line 20
def parallel_process

  @content_array.each_with_index do |item, i|
    text = ''
    request = Typhoeus::Request.new(TxTranslate::TencentFy.new(item).full_request_url.to_s, followlocation: true)

    request.on_complete do |response|
      json = JSON.parse(response.body)

      text = if json['Response']['Error']
               TxTranslate::TencentFy.new(item).full_request_url
             else
               json['Response']['TargetText']
             end
      puts text
      @result_array[i] = text
    end

    @hydra.queue(request)
    sleep(1.0/process_amount)
    @hydra.run
  end

  @result_array
end
process_amount() click to toggle source
# File lib/tx_translate/parallel_array.rb, line 9
def process_amount
  TxTranslate.config[:process_amount] || 5
end