How to create hash hashes inside .each in Ruby

I am working on a Rails application that tracks various events and their statuses.

Here is my Status model:

 class Status < ActiveRecord::Base attr_accessible :value has_many :events end 

There is an interface for adding additional types of states.

My Event model is as follows:

 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.

With this I can do:

 Event.outage 

or

 Event.slow 

and I will return to ActiveRecord::Relation all events with this status. This works as expected.

I have a view that dynamically generates some charts using Highcharts . Here is 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 would like to generate this hash dynamically with a list of Status types from the database:

 <% { "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 a hash to create my diagrams. This does not give me a hash, but it gives me an Array , like Status.all itself.

+4
source share
1 answer

Here is how I would do it, Enumerable#each_with_object and Object#send :

 hash = Status.select(:value).each_with_object({}) do |s, h| h[s.value.upcase] = Event.send s.value.downcase end 
+2
source

All Articles