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

nop*_*ole 51 ruby-on-rails restful-authentication

我以为我们会这样做

helper_method :current_user, :logged_in?, :authorized?
Run Code Online (Sandbox Code Playgroud)

使这些控制器方法可用作视图中的辅助方法.但在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
Run Code Online (Sandbox Code Playgroud)

为什么这样做而不是那条单行呢?而且,我没有看到included任何地方被召唤.

nat*_*vda 96

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

更多信息:ruby mixin教程.


Rya*_*igg 12

AuthenticatedSystem使用该include方法包含该方法时,该self.included方法将被包含在其中作为参数的任何内容触发base.

您显示的代码调用helper_method并定义了一些有用的帮助程序,但前提是它base有一个helper_method方法.

它是这样完成的,因此包括模块可以设置辅助方法以及向类添加其他方法.


Faa*_*lak 12

出于与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
Run Code Online (Sandbox Code Playgroud)

Test.new.abc#=> abc表单测试

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

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

来自Module2的Test.foo#=> foo

来自Module2的Test.bar#=> bar

extend:方法可以作为类方法访问

include:方法将作为实例方法使用

self.extended(base)/ self.included(base)中的" base " :

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

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


Pet*_*per 5

因为这是在Google上搜索“ self.included(base)”的第一个结果,所以我将尝试给出一个有关其工作原理的小例子。我不知道它与Restful身份验证方法有何不同。

基本上,它用于使一个模块中的方法在另一模块中可用。

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
Run Code Online (Sandbox Code Playgroud)

  • 感谢您的回答,但是可以简单地在模块“Two”中添加一行:“include One”,结果将是相同的,不是吗?通过“self.included(base)”方法执行此操作有什么好处? (2认同)