The send_sms_message
method takes text
as an argument. The length of text
is unknown and can be 0 or as large as 1070 (after that we will have no space for the actual text, because multi-part message text will be so long).
The trick is that if text
is larger then 160 characters, we need to split it into parts and to each part add text part 1 of 2.
The problem is that we don't know the length of the extra text. It can be 14 characters for part 1 of 2 or 16 for part 11 of 99 and so on.
This code can handle up to 99 parts. How can I make it generic to handle more parts without adding more conditions?
SMS_LENGTH = 160
MPM_SIZE_LONG = 16
MPM_SIZE_SHORT = 14
MPM_SHORT_LIMIT = 1314
def send_sms_message(text, to, from)
unless text.length > SMS_LENGTH
deliver_message_via_carrier(text, to, from)
else
parts = text.scan(/.{1,#{SMS_LENGTH - (text.length > MPM_SHORT_LIMIT ? MPM_SIZE_LONG : MPM_SIZE_SHORT)}}/)
parts.to_enum.with_index(1) do |message_part, index|
deliver_message_via_carrier("#{message_part} - Part #{index} of #{parts.length}", to, from)
end
end
end