【问题标题】:The reason why it's possible to use helper method like current_user, authenticate_user!, and so on without including any module可以使用 current_user、authenticate_user! 等辅助方法而不包含任何模块的原因
【发布时间】:2021-10-03 16:59:31
【问题描述】:

标题是我的问题。

devise 为我们提供了许多有用的方法,如current_userauthenticate_user! 等。我想知道为什么可以在不包含任何模块的情况下使用它们。

class ApplicationController < ActionController::Base
  before_action :authenticate_user!
end

那些方法的定义是here

有人请帮帮我!

【问题讨论】:

  • 当您在routes.rb 中使用devise_for 时,Devise 会查找您的 ApplicationController 并动态定义方法。如果您想详细了解它的工作原理,您确实需要查看源代码。
  • 补充 max 上面所说的:设计,像大多数 gem 一样,使用 Ruby 中的元编程来实现其目标。 Devise 用于为current_ 生成动态方法的源代码可见:github.dev/heartcombo/devise/tree/master/lib/devise/controllers

标签: ruby-on-rails devise warden


【解决方案1】:

答案是devise included its helper methods into ActionControlleron_loadRails 时代表你

# devise/rails.rb
module Devise
  class Engine < ::Rails::Engine
    # ...
    initializer "devise.url_helpers" do
      Devise.include_helpers(Devise::Controllers)
    end
    # ...
end

# devise.rb
  # ...
  def self.include_helpers(scope)
    ActiveSupport.on_load(:action_controller) do
      include scope::Helpers if defined?(scope::Helpers)
      include scope::UrlHelpers
    end

    ActiveSupport.on_load(:action_view) do
      include scope::UrlHelpers
    end
  end
  # ...   

我看到许多第三个 gem 使用 on_load 将它们的方法(或它们自己)包含到 Rails 核心中,也许这是一种典型的方法(允许 Rails 延迟加载大量组件,从而使应用程序启动更快) .如果你安装了一些 gems 并且你可以在你的模型/控制器/视图上使用它们的方法,那么这些 gems 做了同样的事情 devise 在上面做了。

关于current_userauthenticate_user! 的这些方法……当它在 Rails 中执行include scope::Helpers 时,它们是dynamic methods devise will generate(参见上面的代码和链接)。

【讨论】:

  • 非常感谢!这真的是我想知道的!我无法找到定义动态方法的方法以及使用on_load 方法加载它们的方法。
【解决方案2】:

所以关于 Rails 的一个非常好的事情是,您可以免费获得很多开箱即用的东西。顶层的其中一项是自动加载。

所以在设计的情况下。当您安装设计并运行generate 命令时,您会在config/initializers/ 文件夹中获得一个devise.rb 文件。该文件总是在服务器启动和重新加载时由 rails 自动加载。这就是所有这些方法都能够在不导入任何东西的情况下使用这些设计方法的原因。

阅读更多rails docs

【讨论】:

    猜你喜欢
    • 2017-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多