Z
ZHANK
面向对象

模块与 Mixin

module 定义命名空间、include/extend/prepend、Mixin 组合

模块与 Mixin

Ruby 模块有两种用途:命名空间(组织常量和方法)和 Mixin(用 include/extend/prepend 混入行为)。

学完本章你将: 掌握 module 命名空间、include/extend/prepend、Mixin 组合。


作为命名空间

ruby
module Api
    module V1
        class UsersController
            def index
                puts "API v1 用户列表"
            end
        end
    end
end

Api::V1::UsersController.new.index

include —— 混入实例方法

ruby
module Loggable
    def log(msg)
        puts "[LOG] #{msg}"
    end
end

class User
    include Loggable  # 混入——log 成为实例方法
end

User.new.log("用户登录")  # [LOG] 用户登录

extend —— 混入类方法

ruby
module ClassMethods
    def find(id)
        puts "查找 #{id}"
    end
end

class User
    extend ClassMethods  # find 成为类方法
end

User.find(1)  # "查找 1"

prepend —— 覆盖原方法

ruby
module Callbacks
    def save
        puts "验证..."
        super  # 调用原方法
        puts "通知..."
    end
end

class User
    prepend Callbacks  # 插入到方法查找链前面

    def save
        puts "保存到数据库"
    end
end

User.new.save
# 验证...
# 保存到数据库
# 通知...