[ROR] 如何在mixin模块中定义类方法(Howto define class methods in a mixin module)

Posted 我看青山多妩媚

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[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"

  

以上是关于[ROR] 如何在mixin模块中定义类方法(Howto define class methods in a mixin module)的主要内容,如果未能解决你的问题,请参考以下文章

怎么理解mixins

检索所有包含特定 mixin 的类定义的正确方法是啥?

django---mixins模块及其GenericAPIView类源码分析

Ruby mixins:扩展和包含

如何使用 webpack 预加载 SASS 自定义实用程序(变量和 mixins)

类型为“type”的枚举类作为mixin