Donato Donato - 2 months ago 23
Ruby Question

ruby string interpolation issue with net/imap library

I am using ruby's built-in imap/net library. There seems to be an issue with string interpolation. The following works fine:

imap = Net::IMAP.new('imap.gmail.com',993, true)
imap.login('myuser@gmail.com','password')
imap.select('INBOX')
ids = imap.search(["SINCE", "26-Sep-2016"])
=> [1, 2]


I used a string literal above. However, when I replace the string literal with the following, an error occurs:

imap = Net::IMAP.new('imap.gmail.com',993, true)
imap.login('myuser@gmail.com','password')
imap.select('INBOX')
ids = imap.search(["SINCE", Time.now.strftime('%d-%b-%y')])
=> Net::IMAP::BadResponseError: Could not parse command


What does only a string literal work when the result of Time.now.strftime is a string literal? This is a standard library in ruby, so for sure it must work. What am I missing?

Answer

%y in Time#strftime is the 2-digit year, and Net::IMAP#search requires a 4-digit year. You want %Y:

Time.now.strftime('%d-%b-%y') # => "28-Sep-16"
Time.now.strftime('%d-%b-%Y') # => "28-Sep-2016"

This isn't just a requirement of Net::IMAP, it's actually defined by the IMAP specification on pages 84 and 85.

Comments