如何优化获取Web内容的Ruby代码?

时间:2014-01-23 21:01:12

标签: ruby-on-rails ruby ruby-on-rails-3 ruby-on-rails-3.2

我们有一个Rails 3.2.12应用程序,它通过发出POST请求从合作伙伴API获取数据。但是,我们发现我们的代码似乎是一个瓶颈,因为处理请求所需的时间比预期的要长。我们可以做任何事情来加速代码吗?

我们应该使用另一个XML解析器吗?有没有更快的方式在Ruby中发布SSL请求?

谢谢!

def ced( ad )
    # Set vars
    u = 'e'
    pw = 'p'
    ad = ad.join ','
    url = 'https://r.e.com/interface.asp?ResponseType=XML&Command=BC' + '&UID=' + u + '&PW=' + pw + '&DL=' + ad
    results = []

    # Invoke API command
    uri = URI.parse url
    http = Net::HTTP.new uri.host, uri.port
    http.use_ssl = true
    http.verify_mode = OpenSSL::SSL::VERIFY_NONE
    req = Net::HTTP::Get.new uri.request_uri
    resp = http.request req

    # Parse API response
    resp_xml = Nokogiri.XML resp.body
    resp_xml.remove_namespaces!
    num_errors = resp_xml.at_xpath('//ErrCount').content

    # Any errors?
    if num_errors != '0'
        error = true

    # No errors, process domains
    else
        resp_xml.xpath('//CheckResult').each do |elem|
            results << {
            :domain => elem.xpath('D').text.downcase,
            :status => case elem.xpath('RRPCode').text
                when '210' then 'a'
                when '211' then 't'
                else
                    error = true
                    'error'
                end
            }
        end
    end

    <truncated>
end

0 个答案:

没有答案
相关问题