Ruby使用include和extend来对class做补充。
假设有一个module:
module Person def about_me puts "This is about me." end end
1, include <module name>
1.1 使模块的方法变成类的实例方法:
class Student include Person end student = Student.new student.about_me # puts "This is about me." Student.about_me # 没有定义此方法,抛出异常。
1.2 如何要让 Student 可以直接调用include module的方法,可以在 def self.included(c) ... end 实现,比如
module Person def about_me puts "This is about me." end def self.included(c) def c.call_me puts "This is class me" end end end
Student.call_me即可直接调用。
2, extend <module name>是直接变成类的类方法 ,相当于class << self.
参考资料: http://www.railstips.org/blog/archives/2009/05/15/include-vs-extend-in-ruby
相关推荐
本文将介绍浅谈Ruby on Rails中的include和extend。include主要用来将一个模块插入到一个类或者其它模块。extend用来在一个对象中引入一个模块,这个类从而也具备了这个模块的方法。
Ruby 1.9+用法 只需使用您希望其实现对象定义的任何方法创建一个模块module RemoteControl # turns the device on def on end # turns the device off def off endend然后在您的类中使用implements方法(也别名为...
无论您打算使用Sorbet的RBI格式还是Ruby 3 / Steep的RBS格式,Sord都是在项目中快速采用类型的理想方法。 Sord具有以下功能: 自动为模块,类和方法生成签名 支持多种参数或返回类型( T.any / | ) 优雅地处理...
这就是为什么您必须创建一个类并使用Comparateur include或extend它并根据需要使用它。 此实现还允许您构建自己的缓存系统。 安装 将此行添加到应用程序的 Gemfile 中: gem 'comparateur' 然后执行: $ bundle...
通过使用钩子方法,可以让我们在Ruby的类或模块的生命周期中进行干预,可以极大的提高编程的灵活性。 与生命周期相关的钩子方法有下面这些: 类与模块相关 Class#inherited Module#include Module#prepended ...
类分析器 用于Ruby类的简单性能分析器。 只需将其包含在您的类的底部,然后让它分析您... include ClassProfiler #include it just before closing the class end 或者,如果您想要更可配置的内容,以仅测量特定的方法
描述 另一个 slugging gem,使用自定义映射选项将字符串转换为 slug。 安装 gem install slugity ... require 'slugity/extend_string' "one + two = three" . to_slug # => "one-plus-two-equals-three" 还
用法 安装它gem install eldritch 要求它require 'eldritch' 使用它(请参阅下面的功能) 默认情况下,eldritch会将DSL注入全局范围。 如果您不希望这样做,则可以要求eldritch/safe而不是eldritch 。 require '...
使用模块重构 目标 识别表明需要重构的“代码气味”。 使用模块重构多余的代码。 概述 在本实验中,我们有一个Artist类和一个Song类。...然后,我们将使用extend和include关键字将模块的功能借给Artist和Song
使用模块重构 目标 识别表明需要重构的“代码气味”。 使用模块重构多余的代码。 概述 在本实验中,我们有一个Artist类和一个Song类。... 然后,我们将使用extend和include关键字将模块的功能借给Ar
Refile :: Mongoid 于扩展名。 安装 ...用法 require "refile/mongoid" class User include Mongoid :: Document extend Refile :: Mongoid :: Attachment attachment :profile_image end 执照