Ruby类继承、抽象类、类拓展混入、代理类实例

2019-09-25 09:47:36刘景俊

    require_dependency 'memberpost' 
end 

3、类拓展混入

ruby的类是单继承的,要实现多继承的功能需要用mixin(参合模式)的方式,即类拓展混入来实现。例子:

module Extract 
  def self.included(base) 
     base.extend(ClassMethods) 
  end 
  module ClassMethods 
     def a 
        p "it was a " 
     end 
  end 
end   
 
class A<ActiveRecord::Base 
  include Extract 
end 
 
A.new.a  #=>"it was a" 

4、代理类

当某个功能是比较复杂的,当然写再lib中,作为一个面向函数的方法去处理很简单,也可以用代理类的方式实现面向对象的调用。

例子:

class A<ActiveRecord::Base
 def generate_schedule
    generator =  Generator::ExcelGenerator.new(self)
    generator.generate_schedule
  end
end

module Generator
  class ExcelGenerator

    attr_reader :excel,:workbook,:a,:worksheet
    attr_accessor :styles

    def initialize(a)
      @excel ||= Axlsx::Package.new
      @workbook ||= @excel.workbook
      @worksheet = @workbook.add_worksheet(:name => '测试生成一个excel文件')
      @a ||= a
      @styles ||= Hash.new
    end
   
    def generate_schedule
        #excel内容的具体定义
    end

  end
end

A.new.generate_schedule 就可以通过代理类ExcelGenerator实现一个A的类实例方法generate_schedule

当然也可以通过include 一个model的方式实现添加类实例方法,有时候也可以混合使用。另外使用代理类的好处在于多个类都需要相同方法的时候可以定义共同的部分,举一个发邮件的例子:


class A<ActiveRecord::Base
    include SendEmail
end

class B<ActiveRecord::Base
    include SendEmail
end

实现引入模块:

module SendEmail
    #include this module to class::A and B
    #use like that--  A.first.send_email
    def send_email
      Email.call_email(self)
    end
end