Search code examples
rubyclassobjectinitializer

Storage of variables without initializing an object? Ruby Gem 'Mail'


Working with the Ruby Gem 'Mail', I am confused as to how variables are able to be stored without initializing an object? For example:

Mail.defaults do
  retriever_method :pop3, :address    => "pop.gmail.com",
                          :port       => 995,
                          :user_name  => '<username>',
                          :password   => '<password>',
                          :enable_ssl => true
end

After which you are able to call methods such as Mail.first and have it return the first message in the mailbox with the configured defaults.

I realize everything in Ruby is an object, even a class, so when require 'mail' is called, does an object containing the the class Mail actually get created and mad available to the program? What exactly is happening here?


Solution

  • The contents of mail.rb are loaded into the file that has the require 'mail' statement.

    After having a look in the gem, mail.rb contains the Mail module, which in turn contains many other require statements.

    mail.rb

    module Mail
      ## skipped for brevity
    
      # Finally... require all the Mail.methods
      require 'mail/mail'
    end
    

    mail/mail.rb

    module Mail
      ## skipped for brevity
    
      # Receive the first email(s) from the default retriever
      # See Mail::Retriever for a complete documentation.
      def self.first(*args, &block)
        retriever_method.first(*args, &block)
      end
    end
    

    So then the methods are made available to your program.