2015-12-02 29 views
2

我有一個正在增長的文件(日誌),需要按塊讀取。 我使用Ajax進行調用以獲取指定數量的行。 我使用File.foreach來讀取我想要的行,但它始終從頭讀取,我只需直接返回我想要的行。如何在Rails中讀取文件塊而不從頭再讀取

示例僞代碼:

#First call: 
    File.open and return 0 to 10 lines 

#Second call: 
    File.open and return 11 to 20 lines 

#Third call: 
    File.open and return 21 to 30 lines 

#And so on... 

反正有使這個?

+1

看看這裏:http://stackoverflow.com/a/5052929/1433751 這應該回答你的問題 – Noxx

回答

1

解決方案1:讀取整個文件

提出的解決方案在這裏:
https://stackoverflow.com/a/5052929/1433751

..是不是在你的情況下,有效的解決方案,因爲它需要你去閱讀所有行每個AJAX請求的文件,即使您只需要日誌文件的最後10行。

這是一個巨大的時間浪費,並且在計算方面,解決時間(即處理大小爲N的塊的整個日誌文件)接近指數求解時間。

解決方案2:尋求

由於您的AJAX調用請求順序線,我們可以讀,使用IO.seekIO.pos前落實尋找到正確的位置更加有效的方法。

這要求您在返回請求的行的同時將一些額外的數據(最後一個文件位置)返回給AJAX客戶端。

然後,AJAX請求變成這種形式的函數調用request_lines(position, line_count),它在讀取所請求的行數之前使服務器能夠IO.seek(position)

下面是該解決方案的僞代碼:

客戶端代碼

LINE_COUNT = 10 
pos = 0 

loop { 
    data = server.request_lines(pos, LINE_COUNT) 
    display_lines(data.lines) 
    pos = data.pos 
    break if pos == -1 # Reached end of file 
} 

Server代碼

def request_lines(pos, line_count) 
    file = File.open('logfile') 

    # Seek to requested position 
    file.seek(pos) 

    # Read the requested count of lines while checking for EOF 
    lines = count.times.map { file.readline if !file.eof? }.compact 

    # Mark pos with -1 if we reached EOF during reading 
    pos = file.eof? ? -1 : file.pos 
    f.close 

    # Return data 
    data = { lines: lines, pos: pos } 
end 
+0

謝謝你fo快速回應。最後的解決方案解決了我的問題 – koxta