Files
nairobi/app/models/newsletter.rb
Bertocq 7cfa7b18f9 Validate Newsletter segment_recipient value
Why:

A Newsletter can only be sent if the are available user recipient emails
and that means the `segment_recipient` value actually corresponds to a
function on the UserSegments class.

We could rely on the UserSegments::SEGMENTS constant as the list of
possible user segments functions that a Newsletter can use to gather
emails, so any value not included in that hash would not be valid.

But to be 100% sure the newsletter can get a recipients_list we should
just check if the UserSegments class has a method with same name as the
`segment_recipient` value.

How:

* Adding an validation method that checks if UserSegment has a method
with same name as the `segment_recipient` value.
* Adding an scenario to the Newsletter model spec to check this
2018-02-21 11:46:16 +01:00

29 lines
661 B
Ruby

class Newsletter < ActiveRecord::Base
validates :subject, presence: true
validates :segment_recipient, presence: true
validates :from, presence: true
validates :body, presence: true
validate :validate_segment_recipient
validates_format_of :from, :with => /@/
def list_of_recipients
UserSegments.send(segment_recipient).newsletter if valid_segment_recipient?
end
def valid_segment_recipient?
segment_recipient && UserSegments.respond_to?(segment_recipient)
end
def draft?
sent_at.nil?
end
private
def validate_segment_recipient
errors.add(:segment_recipient, :invalid) unless valid_segment_recipient?
end
end