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
This commit is contained in:
@@ -4,14 +4,25 @@ class Newsletter < ActiveRecord::Base
|
||||
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
|
||||
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
|
||||
|
||||
@@ -261,6 +261,10 @@ en:
|
||||
attachment:
|
||||
min_image_width: "Image Width must be at least %{required_min_width}px"
|
||||
min_image_height: "Image Height must be at least %{required_min_height}px"
|
||||
newsletter:
|
||||
attributes:
|
||||
segment_recipient:
|
||||
invalid: "The user recipients segment is invalid"
|
||||
map_location:
|
||||
attributes:
|
||||
map:
|
||||
|
||||
@@ -257,6 +257,10 @@ es:
|
||||
attachment:
|
||||
min_image_width: "La imagen debe tener al menos %{required_min_width}px de largo"
|
||||
min_image_height: "La imagen debe tener al menos %{required_min_height}px de alto"
|
||||
newsletter:
|
||||
attributes:
|
||||
segment_recipient:
|
||||
invalid: "El segmento de usuarios es inválido"
|
||||
map_location:
|
||||
attributes:
|
||||
map:
|
||||
|
||||
Reference in New Issue
Block a user