Rails: Chartkick cummulative user graph

半腔热情 提交于 2019-12-02 04:25:15

If I understand your question, you need to manipulate the hash of data.

In controller do somehing like this:

@data = User.group_by_week(:created_at).count
accumulator = 0
@data.transform_values! do |val|
  val += accumulator
  accumulator = val
end

Then show the chart in view as <%= line_chart @data %>

If you inspect the hash <%= User.group_by_week(:created_at).count.inspect %> it becomes clear.

In order to use accumulator over any hash, could be useful to add a custom method to Class hash.

module HashPatch
  def accumulate_values!
    accumulator = 0
    transform_values! do |val|
      val+= accumulator
      accumulator = val
    end
  end
end
Hash.include HashPatch

points = {'x1' => 0, 'x2' => 10, 'x3' => 10, 'x4' => 10.1}
points.accumulate_values! #=> {"x1"=>0, "x2"=>10, "x3"=>20, "x4"=>30.1}

transform_values! since Ruby v4.2.1

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!