Sometimes in software you should alter the requirements to simplify the life of everyone (including the business people presumably asking for this to be done).
I would push back against the requirement to pre-calculate the total number of messages. Rather than pre-calculating utilize an end of message marker instead (the text END
should suffice).
I used the solution below to simulate sending an entire book via SMS, and it required fewer than 700 messages total.
For example, if you changed your message format to exclude the "... of X" portion, and did the following instead:
<msg part > - Part 1
<msg part > - Part 2
...
...
...
<msg part> - Part 12657
END
... then your implementation becomes much more straightforward (though even this sample implementation should be cleaned up):
MULTIPART_SUFFIX = ' - Part '
def deliver_message_via_carrier(text, to, from)
puts text
end
def send_sms_message(text, to, from)
chars = text.chars
counter = 0
if text.length <= 160
deliver_message_via_carrier(text, to, from)
else
while chars.length > 0
counter += 1
suffix_text = "#{MULTIPART_SUFFIX}#{counter}"
msg_part = chars.shift(160 - suffix_text.length).join('')
deliver_message_via_carrier("#{msg_part}#{suffix_text}", to, from)
end
deliver_message_via_carrier('END', to, from)
end
end
send_sms_message(text, :sender, :receiver)
...and you get the following benefits:
- Can send messases of arbitrary length (though let's be honest - you'll probably never send more than 1,000,000 messages, so supporting messages of length 10^70 -- many, many times the total amount of data that all of humanity has ever stored -- is highly dubious).
- Your message suffix is shorter, so you wind up saving many characters per message, resulting in many fewer total messages for any message you're likely to actually send.
- This alternative format allows you to easily make every partial message exactly 160 characters in length, which is more efficient on a per-message basis.
- Your code's logic is much simpler, and therefore easier to maintain.
- Messages are still able to be sorted on the receiving end if necessary (i.e. if they are received out-of-order for some reason), because they are individually numbered.