2016-03-03 100 views
1

目前設置一個graph小部件,作業應傳遞到顯示的所有值:如何保存並顯示破折號的歷史數據?

data = [ 
    { "x" => 1980, "y" => 1323 }, 
    { "x" => 1981, "y" => 53234 }, 
    { "x" => 1982, "y" => 2344 } 
    ] 

我想從我的服務器只閱讀當前(最新)的價值,但也應顯示以前的值。

它看起來像我可以create a job,它將從服務器讀取當前值,但剩餘的值將從Redis中讀取(或sqlite database,但我更喜歡Redis)。之後的當前值應該保存到數據庫中。

我從來沒有使用Ruby和Dashing之前,所以我有第一個問題 - 這可能嗎?如果我將使用Redis,那麼問題是如何存儲數據,因爲這是鍵值數據庫。我可以保留它作爲widget-id-1,widget-id-2,widget-id-3 ... widget-id-N等,但在這種情況下,我將不得不存儲N值(如widget-id=N)。或者,有沒有更好的辦法?

回答

0

我來到了以下解決方案:如果

require 'redis' # https://github.com/redis/redis-rb 
redis_uri = URI.parse(ENV["REDISTOGO_URL"]) 
redis = Redis.new(:host => redis_uri.host, :port => redis_uri.port, :password => redis_uri.password) 

if redis.exists('values_x') && redis.exists('values_y') 
    values_x = redis.lrange('values_x', 0, 9) # get latest 10 records 
    values_y = redis.lrange('values_y', 0, 9) # get latest 10 records 
else 
    values_x = [] 
    values_y = [] 
end 

SCHEDULER.every '10s', :first_in => 0 do |job| 
    rand_data = (Date.today-rand(10000)).strftime("%d-%b") # replace this line with the code to get your data 
    rand_value = rand(50) # replace this line with the code to get your data 
    values_x << rand_data 
    values_y << rand_value 

    redis.multi do # execute as a single transaction 
    redis.lpush('values_x', rand_data) 
    redis.lpush('values_y', rand_value) 
    # feel free to add more datasets values here, if required 
    end 

    data = [ 
    { 
     label: 'dataset-label', 
     fillColor: 'rgba(220,220,220,0.5)', 
     strokeColor: 'rgba(220,220,220,0.8)', 
     highlightFill: 'rgba(220,220,220,0.75)', 
     highlightStroke: 'rgba(220,220,220,1)', 
     data: values_y.last(10) # display last 10 values only 
    } 
    ] 
    options = { scaleFontColor: '#fff' } 

    send_event('barchart', { labels: values_x.last(10), datasets: data, options: options }) 
end 

不知道一切是正確實施這裏,但它的工作原理。