What if we have 1,000 announcements and 50,000 users? There are a few ways to test performance of a specific method, one of which is a benchmarking gem from Viget Labs. I used Ruby’s built-in benchmark module.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

# spec/models/announcement_spec.rb

# other rspec tests here...

it"retrieves the latest announcement"do

require'benchmark'

(1..500).eachdo

Announcement.create(:limit_to_users=>[

{

:field=>"subscription",

:value=>""

}

])

end

(1..10000).eachdo

create(:user,:subscription=>"")

end

Benchmark.realtime{

Announcement.current(User.last)

}

end

The call to Announcement still comes in at under 1 ms with 10,000 users and 5,000 announcements.

Showing announcements

A view helper called current_announcement will call the current announcement from the model.

1

2

3

4

5

6

7

8

9

# app/helpers/announcements_helper.rb

module AnnouncementsHelper

def current_announcement

ifdefined?current_user

@current_announcement||=Announcement.current(current_user)

end

end

end

Then, the developer using the gem can pull in the current announcement through a view partial.

1

2

3

4

5

6

7

# app/views/announcements/_announcements_foundation.rb

<%ifcurrent_announcement%>

<div data-alert class="alert-box"id="one-time-announcement">

<%=current_announcement.body.html_safe%>

</div>

<%end%>

We still need to let the user close the announcement, and remember the announcements that each user has read.

This is part 3 of building a gem for targeted, one-time announcements to users in Rails. See part 2 and part 1.

We’ll focus on targeting announcements to certain types of users. For instance, the admin may want to deliver an announcement only to users who have subscriptions.

A field in the Announcements table called limit_to_users will specify which types of users should receive the announcement.

limit_to_users can contain multiple conditions, so we’ll make it an array of hashes. ActiveRecord allows objects like these to be stored in text fields in the database, using the serialize method in a model.

1

2

app/models/announcement.rb

serialize:limit_to_users

This test validates that the field works as intended, storing conditions and allowing them to be retrieved. Here, we are sharing the announcement only with users who do not have a subscription.

In part 1, I talked about the need to announce things to users in a Rails app. The announcements should be scheduled, shown to each user only once, and targeted to particular types of users.

We’re building a Ruby gem to enable this.

Tests

I started by writing tests, describing what the one-time announcements gem should do. Test driven development (TDD) can be controversial, but I find that it helps me plan and identify issues earlier in development.