在Ruby on Rails的Restful身份验证中,#self.included(base)是什么?(What does #self.included(base) do in Ruby on Rails' Restful Authentication?)
我以为我们会做
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被调用在任何地方。
I thought we would do
helper_method :current_user, :logged_in?, :authorized?to make these controller methods available for use as helper methods in views. But in Restful Authentication's lib/authenticated_system.rb, I see:
# 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 endWhy is it done this way instead of that single line? Also, I don't see included being called anywhere.
最满意答案
在包含模块时调用self.included函数。 它允许在基础(包括模块的位置)的上下文中执行方法。
更多信息: 一个ruby mixin教程 。
The self.included function is called when the module is included. It allows methods to be executed in the context of the base (where the module is included).
More info: a ruby mixin tutorial.
更多推荐
发布评论