Rorshark
Rorshark

Reputation: 87

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.

Here's my Status model:

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:

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'll get back an ActiveRecord::Relation of all events with that status. This works as expected.

I have a view that generates some graphs dynamically using 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:

<% { 
     "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. This doesn't give me a hash though, it gives me an Array, just like Status.all would by itself.

Upvotes: 4

Views: 132

Answers (1)

Kyle
Kyle

Reputation: 22258

This is how I would do it, with 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

Upvotes: 2

Related Questions