我正在寻找优化此代码的最佳方法,我们在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 },
答案 0 :(得分:0)
在不知道更新此数据的频率的情况下,很难提出改进建议。如果这只是每日更新,那么您应该安排所有数据脱机更新,并且每天只创建一次文件。如果目标是对数据进行实时更新,那么你肯定会采用错误的方式。
最终,您不应该在Web请求期间更新文件。您应该将文件更新卸载到调度程序或某种类型的队列(如Sidekiq)。或者,如果您需要实时更新数据,则需要查找不同的源并使用WebSocket或Server Sent Events来使用数据。每隔几秒轮询一次更新也是有效的。