[英]How do I create a hash of hashes inside of a .each in Ruby
I'm working on a Rails application that tracks different events and their statuses. 我正在开发一个跟踪不同事件及其状态的Rails应用程序。
Here's my Status
model: 这是我的
Status
模型:
class Status < ActiveRecord::Base
attr_accessible :value
has_many :events
end
There is an interface to add additional status types. 有一个界面可以添加其他状态类型。
My Event
model looks like this: 我的
Event
模型如下所示:
class Event < ActiveRecord::Base
attr_accessible :status_id
belongs_to :status
class << self
Status.all.each do |status|
define_method(status.value.downcase) do
send("where", :status_id => Status.find_by_value(status.value.downcase))
end
end
end
end
So for example I have three different status values: Outage
, Slow
, Error
, etc. 因此,例如,我有三个不同的状态值:
Outage
, Slow
, Error
等。
With this I can do: 有了这个我可以做:
Event.outage
or: 要么:
Event.slow
and I'll get back an ActiveRecord::Relation
of all events with that status. 然后我将返回具有该状态的所有事件的
ActiveRecord::Relation
。 This works as expected. 这按预期工作。
I have a view that generates some graphs dynamically using Highcharts . 我有一个视图,该视图使用Highcharts动态生成一些图形。 Here's my view code:
这是我的查看代码:
<script type="text/javascript" charset="utf-8">
$(function () {
new Highcharts.Chart({
chart: { renderTo: 'events_chart' },
title: { text: '' },
xAxis: { type: 'datetime' },
yAxis: {
title: { text: 'Event Count' },
min: 0,
tickInterval: 1
},
series:[
<% { "Events" => Event,
"Outages" => Event.outage,
"Slowdowns" => Event.slow,
"Errors" => Event.error,
"Restarts" => Event.restart }.each do |name, event| %>
{
name: "<%= name %>",
pointInterval: <%= 1.day * 1000 %>,
pointStart: <%= @start_date.to_time.to_i * 1000 %>,
pointEnd: <%= @end_date.to_time.to_i * 1000 %>,
data: <%= (@start_date..@end_date).map { |date| event.reported_on(date).count}.inspect %>
},
<% end %>]
});
});
</script>
<div id="events_chart"></div>
I'd like to generate this hash dynamically with a list of Status
types from the database: 我想使用数据库中的
Status
类型列表动态生成此哈希:
<% {
"Outage" => Event.outage,
"Slow" => Event.slow,
"Error" => Event.error,
"Restart" => Event.restart }.each do |name, event|
%>
using something like this: 使用这样的东西:
hash = Status.all.each do |status|
hash.merge("#{status.value}" => Event) ||= {}
end
I want to call each
on the hash to generate my charts. 我想对
each
散列调用以生成图表。 This doesn't give me a hash though, it gives me an Array
, just like Status.all
would by itself. 但是,这不会给我哈希,而是给我一个
Array
,就像Status.all
本身一样。
This is how I would do it, with Enumerable#each_with_object
and Object#send
: 这就是我使用
Enumerable#each_with_object
和Object#send
:
hash = Status.select(:value).each_with_object({}) do |s, h|
h[s.value.upcase] = Event.send s.value.downcase
end
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.