美文网首页
Ruby module 模组

Ruby module 模组

作者: paul_deng | 来源:发表于2020-03-08 10:42 被阅读0次

    1. Module 的概念

    In Ruby, modules are somewhat similar to classes: they are things that hold methods, just like classes do. However, modules can not be instantiated. I.e., it is not possible to create objects from a module. And modules, unlike classes, therefore do not have a method new.

    2. Module 与 class

    父子关系

    在讲解 module 时,绕不开的是它与 class 的对比。
    先看看看 class 与 module 的千丝万缕:

    > Class.superclass
    => Module
    

    可以看到,class 是 module 的子。

    能力差别

    > Class.instance_methods - Module.instance_methods
    => [:allocate, :new, :superclass,...]
    
    • Module 是不能实例化的。所以没有 allocate 与 new 方法
    # allocate 与 new 的区别
    class Test
      def initialize(test=5566)
        @test = test
      end
    end
    
    aaa = Test.new
    => #<Test:0x007fc9228e1ff0 @test=5566>
    
    bbb = Test.allocate
    => #<Test:0x007fc923c928d8>
    
    • Module 是不能被 module 继承的。所以没有 superclass
      但是 module 里可以 包含其他 module。Module 可以解决多集成的问题。

    3. Module 的 mixin 用法

    Mixin 为类的实例化方法

    通过 include 可以将 module 的方法混入到类的实例化方法中

    module Tryable
      def who_am_i
        "我屬於#{self.class}"
      end
    end
    
    class RubyGirl
      include Tryable
    end
    
    annie = RubyGirl.new.who_am_i
    => "我屬於RubyGirl"
    

    Mixin 为类方法

    通过 extend 可以将 module 的方法混入到类的类方法中

    module Tryable
      def who_am_i
        "我屬於#{self.class}"
      end
    end
    
    class RubyGirl
      extend Tryable
    end
    
    RubyGirl.who_am_i
    => "我屬於Class"
    

    也可以使用 include 的方式改写,这样只能是类方法,如下:

    module Tryable
      def self.included(base_class)
        base_class.class_eval do
          def self.who_am_i
            "我屬於#{self.class}"
          end
        end
      end
    end
    
    class RubyGirl
      include Tryable
    end
    
    RubyGirl.who_am_i
    => "我屬於Class"
    

    4. Module 与 ActiveSupport::Concern(关系)

    Concern 集成 include 与 extend

    假设,我们需要在 Post & Advertisement 都同时需要以下内容,并且实现是一样的:

    • scope :active
    • active? instances method
    • all_active class method
    class Post < ActiveRecord::Base
    
      # scopes
      scope :active, lambda { |active|
        where(is_active: true)
      }
    
      # instances method
      def active?
        is_active
      end
    
      # class method
      def self.all_active
        puts 'Update all data'
      end
    end
    
    class Advertisement < ActiveRecord::Base
    
      # scopes
      scope :active, lambda { |active|
        where(is_active: true)
      }
    
      # instances method
      def active?
        is_active
      end
    
      # class method
      def self.all_active
        puts 'Update all data'
      end
    end
    

    调用方式分别为:

    Post.active # scope
    Post.new.active? # instance method
    Post.all_active # class method
    
    

    使用上面提及的 module 的应用,及 DRY(Don't Repeat Yourself)原则,可以改为:

    # 需要定义多个 modules
    module ActAsActivable
    
      module ClassEval
        # ClassEval 没有 scope 的定义,无法直接引用。所以在 ActiveModel include 后通过类去动态创建
        def self.included(base_clazz) 
          base_clazz.class_eval do
            scope :active, lambda { |active|
              where(is_active: true)
            }
          end
        end
      end
    
      # 示例方法 module
      module InstanceMethods
        def active?
          is_active
        end
      end
    
      # 类方法 module
      module ClassMethods
        def all_active
          puts 'Update all data'
        end
      end
    end
    
    class Post < ActiveRecord::Base
      include ActAsActivable::ClassEval
      include ActAsActivable::InstanceMethods
      extend ActAsActivable::ClassMethods
    end
    
    class Advertisement < ActiveRecord::Base
      include ActAsActivable::ClassEval
      include ActAsActivable::InstanceMethods
      extend ActAsActivable::ClassMethods
    end
    

    也可以编写为,这样应用更简便:

    module ActAsActivable
      def self.included(base)
        base.send(:include, InstanceMethods)
        base.extend ClassMethods
        base.class_eval do
          scope :active, lambda { |active|
            where(is_active: true)
          }
        end
      end
    
      # 示例方法 module
      module InstanceMethods
        def active?
          is_active
        end
      end
    
      # 类方法 module
      module ClassMethods
        def all_active
          puts 'reload all data'
        end
      end
    end
    
    class Post < ActiveRecord::Base
      include ActAsActivable
    end
    
    class Advertisement < ActiveRecord::Base
      include ActAsActivable
    end
    

    Concern 有点类似上面的简单写法,并且更加简练,容易读懂。Concern 提供了同时混入多种类型模块的操作。

    module ActAsActivable
      extend ActiveSupport::Concern
    
      included do |base|
        scope :active, lambda { |active|
          where(is_active: true)
        }
      end
    
      module ClassMethods
        def all_active
          puts 'reload all data'
        end
      end
    
      # instance methods
      def active?
        is_active
      end
    end
    
    

    Concern 解决多层依赖问题

    module Foo
      # base 不会取最顶层的 class, 只有直接 mixin Foo 的,才能拥有类方法 foo_parent_method
      # 所以不能通过 Bar 传递到 Host
      def self.included(base)
        base.class_eval do
          def self.foo_parent_method
            puts 'Hello, I am defined at module Foo'
          end
        end
      end
    end
    
    module Bar
      # mixin 后,能直接使用 Bar.foo_parent_method
      include Foo
      
      # Host include Bar后, 就会执行 Host.foo_parent_method
      def self.included(base_class)
        base_class.foo_parent_method
      end
    end
    
    class Host
      include Foo # Host 也是需要单独 mixin,才能使用 Host.foo_parent_method
      include Bar
    end
    

    或者写作:

    module Foo
      # 谁 extend Foo,谁便有了类方法 foo_parent_method
      def foo_parent_method
        puts 'Hello, I am defined at module Foo'
      end
    end
    
    module Bar
      # mixin 后,能直接使用 Bar.foo_parent_method
      extend Foo
      
      # Host include Bar后, 就会执行 Host.foo_parent_method
      def self.included(base_class)
        base_class.foo_parent_method
      end
    end
    
    class Host
      extend Foo
      include Bar
    end
    

    Host <(mixin) Bar < (mixin) Foo,为什么 Host 还是需要 mixin Foo 呢?

    Bar include 的 Foo,里面动态生成了类方法是基于 Bar 的,只能 Bar.foo_parent_method 这样子调用。

    当 Host include Bar 后,Foo 的类方法是无法直接突破两层,作为 Host 直接使用,必须在 Host extend Foo,才能有 Foo 定义的类方法。

    这里只是举例子,实际可以将 Bar 改为以下内容,Host 就不需要依赖 Foo 了,但是很难避免 Foo 同时被 Bar 和 Host 依赖的情况(如 Foo 的类方法需要动态获取 class 的信息,如 class name)。

    module Bar
      # mixin 后,能直接使用 Bar.foo_parent_method
      extend Foo
      
      # Host include Bar 后,只会执行 Bar.foo_parent_method
      def self.included(base_class)
        self.foo_parent_method
      end
    end
    

    Concern 可以有效解决这种多层依赖的问题,它的 included 里的 self 使用的是最顶层的 class。

    module Foo
      extend ActiveSupport::Concern
      
      included do
        class_eval do
          def self.foo_parent_method
            puts 'Hello, I am defined at module Foo'
          end
        end
      end
    end
    
    module Bar
      extend ActiveSupport::Concern
      include Foo
    
      included do
        self.foo_parent_method
      end
    end
    
    class Host
      include Bar
    end
    

    注意,如果把 Foo 改成:

    module Foo
      extend ActiveSupport::Concern
      
      # 谁 extend Foo,谁便有了类方法 foo_parent_method
      def foo_parent_method
        puts 'Hello, I am defined at module Foo'
      end
    end
    
    module Bar
      extend Foo
    end
    
    module Host
      include Bar
    end
    

    执行 Host.foo_parent_method 是无效的,只能执行 Bar.foo_parent_method

    所以解决依赖的只适用于使用 include 实现 mixin

    5. 参考

    Ruby女孩(24):模組是不生孩子的!模組與類別差異及mixin介紹

    软件设计原则——DRY(Dont Repeat Yourself)和KISS( Keep It Simple, Stupid)

    instance_eval 與 class_eval 差異

    ActiveSupport::Concern 小结

    ActiveSupport::Concern 的工作原理

    Ruby for beginners - Modules

    相关文章

      网友评论

          本文标题:Ruby module 模组

          本文链接:https://www.haomeiwen.com/subject/ztqddhtx.html