Ruby, Ruby on Rails

Group_by – The Definitive Guide

I’ve been working on a Rails API that sends JSON goodness to a mobile app. Its the first major app I’ve done that involves me doing the API side.

(I’ve learned that designing APIS is NOT as easy as I thought. Especially when other people have to use them.)

One of the things I had to do was to send a json load of bookings grouped by the
type of facility that was booked.

I admit I don’t religiously read the API docs for any programming language I work on, so I was embarrassingly excited when I found the group_by method

Lets read the official explaination

Collect an enumerable into sets, grouped by the result of a block. Useful, for example, for grouping records by date.

So lets break it down

1) It takes an enumerable, and like all enumerables it iterates through its contents

2) It then groups everything it iterates based on the results of the block

So imagine I had an ActiveRecordRelation with 3 booking objects

@bookings = [
  # 1,
    :facility_name => "BBQ",
    :booking_date => Wed, 30 Nov 2016>,
  # 3,
    :facility_name => "Sauna",
    :booking_date => Wed, 23 Nov 2016>,
  # 2,
    :facility_name => "BBQ",
    :booking_date => Thu, 24 Nov 2016>
]

So what if I want to group these bookings by facility name? I would do something like this.

   grouped_bookings = @bookings.group_by{ |b| b.facilty_name }

grouped_booking will return

@bookings = 
  {
    "BBQ" => [
    # 1,
      :facility_name => "BBQ",
      :booking_date => Wed, 30 Nov 2016>,
    # 2,
      :facility_name => "BBQ",
      :booking_date => Thu, 24 Nov 2016>
  ],
    "Sauna" => [
      # 3,
      :facility_name => "Sauna",
      :booking_date => Wed, 23 Nov 2016>,
    ]
  }

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s