Extract methods to get recipients and valid segments

This way we don't have to use the `send` method in other places, like
the AdminNotification class, and we can change the internal
implementation at any point.
This commit is contained in:
Javi Martín
2021-11-10 20:45:00 +01:00
parent 78e543f6d3
commit 7a028411ab
4 changed files with 34 additions and 4 deletions

View File

@@ -13,11 +13,11 @@ class AdminNotification < ApplicationRecord
before_validation :complete_link_url
def list_of_recipients
UserSegments.send(segment_recipient) if valid_segment_recipient?
UserSegments.recipients(segment_recipient) if valid_segment_recipient?
end
def valid_segment_recipient?
segment_recipient && UserSegments.respond_to?(segment_recipient)
UserSegments.valid_segment?(segment_recipient)
end
def draft?

View File

@@ -15,7 +15,7 @@ class Newsletter < ApplicationRecord
end
def valid_segment_recipient?
segment_recipient && UserSegments.respond_to?(segment_recipient)
UserSegments.valid_segment?(segment_recipient)
end
def draft?

View File

@@ -57,8 +57,16 @@ class UserSegments
)
end
def self.valid_segment?(segment)
segment && respond_to?(segment)
end
def self.recipients(segment)
send(segment)
end
def self.user_segment_emails(segment)
UserSegments.send(segment).newsletter.order(:created_at).pluck(:email).compact
recipients(segment).newsletter.order(:created_at).pluck(:email).compact
end
private

View File

@@ -21,6 +21,28 @@ describe UserSegments do
end
end
describe ".valid_segment?" do
it "returns true when the segment exists" do
expect(UserSegments.valid_segment?("all_proposal_authors")).to be true
expect(UserSegments.valid_segment?("investment_authors")).to be true
expect(UserSegments.valid_segment?("feasible_and_undecided_investment_authors")).to be true
end
it "accepts symbols as parameters" do
expect(UserSegments.valid_segment?(:selected_investment_authors)).to be true
expect(UserSegments.valid_segment?(:winner_investment_authors)).to be true
expect(UserSegments.valid_segment?(:not_supported_on_current_budget)).to be true
end
it "is falsey when the segment doesn't exist" do
expect(UserSegments.valid_segment?("imaginary_segment")).to be_falsey
end
it "is falsey when nil is passed" do
expect(UserSegments.valid_segment?(nil)).to be_falsey
end
end
describe ".all_users" do
it "returns all active users enabled" do
active_user = create(:user)