2016-03-03 98 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 

不知道一切是正确实施这里,但它的工作原理。