简体   繁体   English

扩展Ruby类的正确方法?

[英]Proper way to extend a Ruby Class?

I am trying to extend the Smtpapi::Header class in order to stay DRY. 我试图扩展Smtpapi :: Header类以保持DRY。 Is this the proper way to set these original Smtpapi setters in my extension? 这是在我的扩展程序中设置这些原始Smtpapi setter的正确方法吗? I am new to Ruby. 我是Ruby的新手。

  class CustomMailerHeader < Smtpapi::Header

    def initialize(params)

        super
    end

    def no_service_header
          self.add_category("Service Down Email")
          self.add_filter('templates', 'enable', 1)
          self.add_filter('templates', 'template_id', '8bawd1-9e66') 
          self.add_substitution('-|A_MESSAGE|-', ['server down'])
          self.set_tos('admin@admin.com')
          self
    end

end

Then use it like this 然后像这样使用

header = CustomMailerHeader.new.no_service_header

That'll work, though CustomMailerHeader.new would just be the same thing as CustomMailerHeader.new so you can abstract away the no_service_header and clean it up a bit: 这样就可以了,尽管CustomMailerHeader.newCustomMailerHeader.new一样,因此您可以抽象出no_service_header并对其进行一些清理:

def initialize
  super
  no_service_header
end

private

def no_service_header
  add_category("Service Down Email")
  add_filter('templates', 'enable', 1)
  add_filter('templates', 'template_id', '8bawd1-9e66') 
  add_substitution('-|A_MESSAGE|-', ['server down'])
  set_tos('admin@admin.com')
end

Usage: 用法:

header = CustomMailerHeader.new

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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