Ruby on rails RubyonRails-优化代码以提高速度创建js文件

Ruby on rails RubyonRails-优化代码以提高速度创建js文件,ruby-on-rails,ruby,Ruby On Rails,Ruby,我正在寻找一种优化这段代码的最佳方法,我们在90行左右的文件中创建了近250个js文件 有什么建议吗 def company_trend_seventy begin @market = Market.find_by_market_opser('TDWL') @market.companies.each do |trend| f = File.new("#{Rails.root}/public/#{trend.api_id}.js", "w+") f.write("var

我正在寻找一种优化这段代码的最佳方法,我们在90行左右的文件中创建了近250个js文件

有什么建议吗

 def company_trend_seventy
begin
  @market = Market.find_by_market_opser('TDWL')
  @market.companies.each do |trend|
    f = File.new("#{Rails.root}/public/#{trend.api_id}.js", "w+")
    f.write("var vix = [ \n ")
    seventy = JSON.parse([open("http://www.google.com/finance/getprices?q=#{trend.api_id}&x=TADAWUL&i=86400&p=90d&f=d,c,o,h,l,v&df=cpct&auto=1&ts=1266701290218").read].to_json)
    @date =  Time.at(seventy.first.strip().split("TIMEZONE_OFFSET=180\n")[1].split("\n").first.split(",")[0][1..-1].to_i)
    seventy.first.strip().split("TIMEZONE_OFFSET=180\n")[1].split("\n").each_with_index do |seventyy,i|
      if i == 0
        new_date = Time.at(seventyy.split(",")[0][1..-1].to_i).strftime("%e-%b-%Y")
      else
        new_date = (@date + seventyy.split(",")[0].to_i.day).strftime("%e-%b-%Y")
      end
      f.write("{ date: '#{new_date}', open: #{seventyy.split(",")[4]}, high: #{seventyy.split(",")[2]}, low: #{seventyy.split(",")[3]}, close: #{seventyy.split(",")[1]}, signal: '0', ret: 0 },\n")
    end
    f.write("];")
  end
  flash[:notice] = "Stock Updated Successfully!"
  redirect_to "/admin/companies"
rescue Exception => ex
  flash[:notice] = "Connection Time out!"
  redirect_to admin_dashboards_path
end
end
文件中的输出如下所示

提前谢谢

var vix = [ 
 { date: '30-Mar-2014', open: 30.9, high: 31.1, low: 30.6, close: 30.8, signal: '0', ret: 0 },
{ date: '31-Mar-2014', open: 30.9, high: 31.5, low: 30.8, close: 31.4, signal: '0', ret: 0 },
{ date: ' 1-Apr-2014', open: 31.5, high: 31.5, low: 31.2, close: 31.4, signal: '0', ret: 0 },
{ date: ' 2-Apr-2014', open: 31.3, high: 31.7, low: 31.3, close: 31.4, signal: '0', ret: 0 },
{ date: ' 3-Apr-2014', open: 31.9, high: 32.6, low: 31.4, close: 32.1, signal: '0', ret: 0 },
{ date: ' 6-Apr-2014', open: 32.3, high: 32.6, low: 31.8, close: 32.1, signal: '0', ret: 0 },
{ date: ' 7-Apr-2014', open: 32.1, high: 32.1, low: 31.4, close: 31.6, signal: '0', ret: 0 },
{ date: ' 8-Apr-2014', open: 31.7, high: 32, low: 31.5, close: 31.9, signal: '0', ret: 0 },
{ date: ' 9-Apr-2014', open: 31.7, high: 31.9, low: 31.4, close: 31.7, signal: '0', ret: 0 },

如果不知道更新这些数据的频率,就很难提出改进建议。如果这只是每日更新,那么您应该计划脱机更新所有数据,并且每天只创建一次文件。如果目标是实时更新数据,那么在这方面你肯定走错了路


最终,您不应该在web请求期间更新文件。您应该将文件更新卸载到调度程序或某种队列(如Sidekiq)。或者,如果需要实时更新数据,则需要找到其他源并使用WebSocket或服务器发送的事件来使用数据。每隔几秒钟轮询一次更新也是有效的。

这个问题应该发布在网站上。没有有效的优化方法,您正在为
http://www.google.com/...
这将占去几乎所有可测量的程序运行时间。最好的优化方法是不要这样做。你可以使用线程来减少IO,但是如果你创建了太多的线程,你可能会耗尽内存。。。