在Ruby on Rails的Restfulauthentication中,#self.included(base)做了什么?

我以为我们会做

helper_method :current_user, :logged_in?, :authorized? 

使这些控制器方法可以在视图中用作辅助方法。 但是在Restful Authentication的lib/authenticated_system.rb ,我看到:

 # Inclusion hook to make #current_user and #logged_in? # available as ActionView helper methods. def self.included(base) base.send :helper_method, :current_user, :logged_in?, :authorized? if base.respond_to? :helper_method end 

为什么这样做而不是那一行呢? 另外,我不认为included被称为任何地方。

包含模块时会调用self.included函数。 它允许方法在基础(包含模块的地方)的上下文中执行。

更多信息: 一个ruby混合教程 。

当使用include方法包含AuthenticatedSystem方法时, self.included方法被触发,无论它被包含为base的参数。

你所显示的代码调用helper_method并定义了一些有用的帮助器,但是只有当它有一个helper_method方法的时候。

这样做,包括模块可以设置辅助方法,以及添加额外的方法的类。

出于与Peter提到的相同的原因,我想添加一个例子,以便新手开发者很容易理解self.included(base)self.extended(base)

 module Module1 def fun1 puts "fun1 from Module1" end def self.included(base) def fun2 puts "fun2 from Module1" end end end module Module2 def foo puts "foo from Module2" end def self.extended(base) def bar puts "bar from Module2" end end end class Test include Module1 extend Module2 def abc puts "abc form Test" end end 

Test.new.abc#=> abc表单testing

来自Module1的Test.new.fun1#=> fun1

来自Module1的Test.new.fun2#=> fun2

来自Module2的Test.foo#=> foo

来自Module2的Test.bar#=> bar

扩展:方法将作为类方法访问

包括:方法将作为实例方法提供

self.extended( base )/ self.included( base )中的“ base ”:

静态扩展方法中的基本参数将是扩展模块的类的实例对象或类对象,分别取决于您是扩展对象还是类。

当一个类包含一个模块时,模块的self.included方法将被调用。 base参数将是包含该模块的类的类对象。

因为这是在Googlesearch“self.included(base)”时的第一个结果,所以我将尝试举一个小例子来说明它的工作原理。 我不知道它与restful-authentication-approach有什么不同。

它基本上是用来从另一个模块中提供一个模块的方法。

 module One def hello puts 'hello from module One' end end module Two def self.included(base) base.class_eval do include One end end end class ExampleClass include Two end ExampleClass.new.hello # => hello from module One 

想挖掘self.included self.extendedself.extended

请看这里: https : //ruby-doc.org/core-2.2.1/Module.html#method-i-included