class Login
def initialize(user, domain, pass)
@username = user
@domain = domain
@pass = pass
#check if gmail or other domain
gmail_test = @domain.include? "gmail.com"
if gmail_test == true
@imap = Net::IMAP.new('imap.gmail.com',993,true,nil,false)
@imap.login(@username + "@" + @domain, @pass)
else
@imap = Net::IMAP.new("mail." + @domain)
@imap.authenticate('LOGIN', @username + "@" + @domain, @pass)
end
return self
end
#enable mailbox select
def mailbox(box)
@mailbox = box
@mailbox_array = @imap.list('','*').collect{ |mailbox| mailbox.name } #create array of mailboxes
@matching_mailbox = @mailbox_array.grep(/#{@mailbox}/i) #search for mailbox along list
if @matching_mailbox.empty? == true #if no results open INBOX
@mailbox = "INBOX"
@imap.examine(@mailbox)
else
@imap.examine(@matching_mailbox.first.to_s) #if multiple results, select first and examine
@mailbox = @matching_mailbox.first.to_s
end
return self
end
end
I want to be able to say:
Login.new("user", "domain", "pass").mailbox("in")
and then something like:
class Stat
def received_today()
#emails received today
@today = Date.today
@received_today = @imap.search(["SINCE", @today.strftime("%d-%b-%Y")]).count.to_s
puts @domain + " " + @mailbox.to_s + ": " + @received_today + " -- Today\n\n" #(" + @today.strftime("%d-%b-%Y") + ")
end
end
And be able to call
Stat.new.received_today and have it not throw a "no method search" error. Again, the other question contains pseudo_code and a high level explanation of how to use an accessor method to do this, but I can't implement it regardless of how many hours I've tried (been up all night)...
All I can think is that I am doing this wrong at a high level, and the stat calculation needs to be a method for the Login class, not a separate class. I really wanted to make it a separate class, however, so I could more easily compartmentalize... Thanks!
Another approach that works and doesn't require defining get_var methods:
b.instance_variable_get("@imap") # where b = class instance of login
def get_imap @imap end def get_domain @domain end def get_mailbox @mailbox end
class Stat def received_today(login) #emails received today @today = Date.today @received_today = login.get_imap.search(["SINCE", @today.strftime("%d-%b-%Y")]).count.to_s # puts @received_today puts login.get_domain + " " + login.get_mailbox.to_s + ": " + @received_today + " -- Today\n\n" end end
search
or imap
:b = Login.new("user", "domain", "pass").mailbox("box") c = Stat.new c.received_today(b)
attr_accessor
or attr_reader
use:login.imap.search#stuff
in class Stat
with no problem.attr_accessor
or attr_reader
use:login.imap.search#stuff
in class Stat
with no problem.