【问题标题】:module not loading in the controller (undefined_method error)模块未加载到控制器中(undefined_method 错误)
【发布时间】:2016-12-03 14:51:19
【问题描述】:

在我看来,在应用BeforeOrAfter 模块之前,尝试让它在控制台中工作。为#`错误获取NoMethodError: undefined methodbefore_or_after':

> s = Artist.find(1)
> s.events.each do |event|
>     before_or_after(event.date)
> end

我选择新建一个modules子目录,app/modules/before_or_after.rb:

module BeforeOrAfter
  attr_reader :past
  attr_reader :future

  require "date"
  def initialize
    @datetime = DateTime.new
    @future = []
    @past = []
  end

  def before_or_after(datetime)
    if datetime < DateTime.now
      @past << datetime
    else
      @future << datetime
    end
  end
end

将它包含在 application_controller.rb 中,因为我所有的控制器都将使用它:

class ApplicationController < ActionController::Base
  include BeforeOrAfter

【问题讨论】:

    标签: ruby-on-rails mixins


    【解决方案1】:

    我不认为 rails 环境在运行控制台之前是预先加载的。如果您在控制台中,请确保在使用该方法之前require 该文件。

    如果您正在运行完整的 Rails 应用程序,那么您的文件应该会自动加载。您可以阅读更多关于自动加载和需要 here 的信息。

    【讨论】:

    • require "before_or_after" 导致 LoadError,没有这样的文件。我知道我正在以不太传统的方式创建 modules/ 子目录,而不是将模块粘贴到 lib/ 中,这可能是问题吗?我正在运行我的开发服务器,重启了很多次。
    • 只有当包含该文件的目录位于 $LOAD_PATH 数组中时,才能仅通过名称来要求模块。您必须使用当前工作目录中的相对路径来要求该文件。
    • 你也应该遵守约定,将该文件放在你的 lib 目录下。
    【解决方案2】:

    要在您的 Rails 应用程序中运行,请在 config/application.rb 中添加以下行,

    config.autoload_paths << Rails.root.join('app/modules')
    

    要在控制台中运行,请首先包含您的模块,

    include BeforeOrAfter
    

    【讨论】:

    • 服务器无法启动,因为配置未定义。那条线应该进入某种块吗?
    • 是的,它必须在 Application 类中 <:application.>
    猜你喜欢
    • 1970-01-01
    • 2020-01-05
    • 1970-01-01
    • 2016-03-24
    • 1970-01-01
    • 2017-04-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多