简体   繁体   中英

Ruby require a module in a module?

I am using the SendGrid module ( require sendgrid-ruby ), but placing code like this everywhere is not very DRY.

client = SendGrid::Client.new(api_key: SENDGRID_KEY)
      mail = SendGrid::Mail.new do |m|
        m.to = 'js@lso.com'
        m.from = 'no-reply@gsdfdo.com'
        m.subject = 'Boo'
        m.html = " "
        m.text = " "
      end

My thought was create a module MyModule that would create a method called standardMail

module MyModule
    require 'sendgrid-ruby'
    def standardMail
          mail = SendGrid::Mail.new do |m|
            m.to = 'js@lso.com'
            m.from = 'no-reply@gsdfdo.com'
            m.subject = 'Boo'
            m.html = " "
            m.text = " "
          end
     return mail
    end 
end

Then can I just use standardMail (via include MyModule ) to return the mail object setup and ready to go. My question is can you require a module in a module ( aka require sendgrid-ruby in my custom module ).

class Thing
  include MyModule

  def doMail
   mail = Thing.standardMail 
  end 
end

I'm not sure why you need a module in this case it would be much easier to extend the default behavior of Sendgrid:

class MyMailer < SendGrid::Mail
 def initialize(params)
    @to = 'js@lso.com'
    @from = 'no-reply@gsdfdo.com'
    @subject = 'Boo'
    @html = " "
    @text = " "

    super
  end
end

Or you can override directly:

class SendGrid::Mail
  def initialize(params)
    @to = 'js@lso.com'
    @from = 'no-reply@gsdfdo.com'
    @subject = 'Boo'
    @html = " "
    @text = " "

    super
  end
end

There is no difference between:

module Foo
  require 'bar'
  # ...
end

and

require 'bar'
module Foo
  # ...
end

So, yes, you can require a module Ruby file inside a module, but there is little reason to do so.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM