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
任何地方被召唤.
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参数将是包含模块的类的类对象.
因为这是在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)
归档时间: |
|
查看次数: |
34348 次 |
最近记录: |