module M
# self.included is the hook which automatically runs when this module is included
def self.included(base)
puts 'this will be printed when this module will be included inside a class'
base.extend ClassMethods
base.class_eval do
scope :disabled, -> { where(disabled: true) }
end
end
def print_object_class
self.class.name # here self will be the object of class which includes this module
end
module ClassMethods
def print_class_name
self.name # Here self would be the class which is including this module
end
end
end
我尝试修改上述module 以帮助您了解模块(关注点)如何有助于代码可重用性
self.included 是一个钩子,当模块包含在类中时会自动运行。
module ClassMethods 中声明的任何方法都将成为包括该模块在内的类的类方法
module ClassMethods 之外声明的任何方法都将成为包括该模块在内的类的实例方法
对于 Ex 假设有一个类 Product 并且你已经在其中包含了模块
class Product < ActiveRecord::Base
include M
puts 'after including M'
end
如果您在 Rails 控制台中尝试此示例,您会注意到,只要模块 M 包含在 class Product 中,就会包含模块运行的钩子和
this will be printed when this module will be included inside a class 打印在控制台上
之后after including M 将打印在控制台上。
你也可以试试下面的命令
Product.disabled # a scope with name 'disabled' is avaialble because of including the module M
Product.print_class_name # Outputs => 'Product' This method is available to class with the help of module M
Product.new.print_object_class #Outputs => 'Product'
它还提供可重用性,将这个模块 M 包含在任何类中,并且该类可以访问模块中描述的所有方法。
而您的第二个示例仅仅是基本模块的示例
module N
def self.abc
puts 'basic module'
end
end
现在 abc 在模块中定义的方法可以仅使用此模块访问
N.abc # outputs 'basic module'
class Product < ActiveRecord::Base
include N
end
Product.abc #引发异常,在类 Product 上找不到方法
Product.new.abc #引发异常,在 Product 类的对象上找不到方法
我希望这可以帮助您更好地理解模块的概念。
如果您仍有任何疑问,请告诉我。