zoukankan      html  css  js  c++  java
  • [ROR] 如何在mixin模块中定义类方法(Howto define class methods in a mixin module)

    方法一: 修改模块的include方法

    module Bbq
      def self.included(base)
        base.send :include, InstanceMethods
        base.extend ClassMethods
      end
    
      module InstanceMethods
        def m1
          'instance method'
        end
      end
    
      module ClassMethods
        def m2
          'this is class method'
        end
      end
    end
    
    class Test
      include Bbq
    end  

    测试:

    irb(main):030:0> Test.m2
    => "this is class method"
    
    irb(main):031:0> Test.m1
    Traceback (most recent call last):
    NoMethodError (undefined method `m1' for Test:Class)
    
    irb(main):032:0> Test.new.m1
    => "instance method"
    

      

    方法二:借助ActiveSupport::Concern

    require 'active_support/concern'
    
    module Bbq2  extend ActiveSupport::Concern
    
      def m1
        'instance method'
      end
    
      class_methods  do
        def m2
          'this is class method'
        end
      end
    end
    
    class Test2
      include Bbq2
    end  
    

      

    测试:

    irb(main):019:0> Test2.m2
    => "this is class method"
    irb(main):020:0> Test2.m1
    Traceback (most recent call last):
    NoMethodError (undefined method `m1' for Test2:Class)
    irb(main):021:0> Test2.new.m1
    => "instance method"
    

      

  • 相关阅读:
    倒下
    我还能相信谁

    工作这点事
    人,这东西
    祝福
    路,公车和鞋子
    那片海
    document.querySelector bug All In One
    js logical or assignment bug All In One
  • 原文地址:https://www.cnblogs.com/dajianshi/p/11453543.html
Copyright © 2011-2022 走看看