no name no name - 2 months ago 6
Ruby Question

How do i loop a specific block in ruby

i want to loop the mail body so it keeps sending the email until ctrl+c is pressed , how do i do that? i have been trying for hours but cant figure it out. Any help would be greatful

Mail.deliver do
to 'mikel@test.lindsaar.net'
from 'ada@test.lindsaar.net'
subject 'testing sendmail'
body 'testing sendmail' #how to loop the body to keep sending email
end

Answer

to start an infinite loop you can go with:

loop do
  # email sending logic here
end

Another option is:

while true
  # email sending logic here
end

Yet another one is:

until false
  # email sending logic here
end

You got the idea. Any of these will only stop when you stop it.

 loop do
  Mail.deliver do
    to 'mikel@test.lindsaar.net'
    from 'ada@test.lindsaar.net'
    subject 'testing sendmail'
    body 'testing sendmail' #how to loop the body to keep sending email
  end
end

EDIT

After the discussion in comments here is how you pass body as an argument:

def send_mail(body) # pass an argument called `body`
  Mail.deliver do
    to      'mikel@test.lindsaar.net'
    from    'ada@test.lindsaar.net'
    subject 'testing sendmail'
    body    body # use passed into the method argument
  end
end

Usage:

send_email('this is a demo body')