【问题标题】:Rails 5 API - error autoloading helper when using the api_only flagRails 5 API - 使用 api_only 标志时错误自动加载帮助程序
【发布时间】:2016-12-21 00:52:55
【问题描述】:

我正在尝试使用文件夹“app/helpers/transaction_helper.rb”中的模块。 (需要注意的是,应用程序正在使用api_only 标志,并且默认情况下不会生成或加载帮助程序。)

module TransactionHelper
  module Generator
    def self.code_alphanumeric(params)
    end
  end
end

我收到了这个错误:

NameError: uninitialized constant TransactionHelper

我尝试将以下行添加到 application.rb

config.autoload_paths += %W(#{config.root}/app/helpers)

require_relative 'boot'

require "rails"
# Pick the frameworks you want:
require "active_model/railtie"
require "active_job/railtie"
require "active_record/railtie"
require "action_controller/railtie"
require "action_mailer/railtie"
require "action_view/railtie"
require "action_cable/engine"
# require "sprockets/railtie"
require "rails/test_unit/railtie"

# Require the gems listed in Gemfile, including any gems
# you've limited to :test, :development, or :production.
Bundler.require(*Rails.groups)

module SistemaControleContasApi
  class Application < Rails::Application
    config.autoload_paths += %W(#{config.root}/app/helpers)
    # Settings in config/environments/* take precedence over those specified here.
    # Application configuration should go into files in config/initializers
    # -- all .rb files in that directory are automatically loaded.

    # Only loads a smaller set of middleware suitable for API only apps.
    # Middleware like session, flash, cookies can be added back manually.
    # Skip views, helpers and assets when generating a new resource.
    config.api_only = true
  end
end

但这直到不起作用。如果我尝试将此文件放在 app/models 目录中,则可以。但是,这不是放置助手的正确本地位置。

有人可以帮忙吗?

【问题讨论】:

  • 与其对抗 API 模式,为什么不将该代码移动到 /lib/transaction_helper/generator 并将该目录添加到您的 autoload_paths?
  • 您可以尝试将config.autoload_paths 替换为config.eager_load_paths 吗?

标签: ruby-on-rails ruby-on-rails-5 autoload


【解决方案1】:

通常,如果您遵循 Rails™ 命名约定,app 下的所有内容都会默认自动加载。见这里Docs。

set_autoload_paths:这个初始化器在 bootstrap_hook 之前运行。添加 应用程序的所有子目录和由指定的路径 config.autoload_paths、config.eager_load_paths 和 config.autoload_once_paths 到 ActiveSupport::Dependencies.autoload_paths。

因此,在第一步中,您应该从配置中删除 config.autoload_paths += %W(#{config.root}/app/helpers)。

然后,您应该为每个模块创建一个子文件夹。
所以对于你的问题,你应该把你的模块放在app/modules/transaction_helper/generator.rb

您也不需要在模块范围内使用self。


我个人会按如下方式创建助手:
module TransactionHelper
  def generate_alphanumeric_code
     # params are automatically available in helpers.
  end
end

并放在app/modules/transaction_helper.rb下。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-09-26
    • 1970-01-01
    • 2015-01-06
    • 1970-01-01
    • 2011-11-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多