Ruby module 模组

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

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 199,902评论 5 468
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 84,037评论 2 377
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 146,978评论 0 332
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 53,867评论 1 272
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 62,763评论 5 360
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,104评论 1 277
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 37,565评论 3 390
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,236评论 0 254
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,379评论 1 294
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,313评论 2 317
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,363评论 1 329
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,034评论 3 315
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 38,637评论 3 303
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,719评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,952评论 1 255
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 42,371评论 2 346
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 41,948评论 2 341

推荐阅读更多精彩内容