【问题标题】:annotate gem not working after including custom module inside model在模型中包含自定义模块后注释gem不起作用
【发布时间】:2021-05-17 03:53:16
【问题描述】:

在模型中包含自定义模块后,注释停止工作并给我错误: 我的模型:app/models/hotel.rb

class Hotel < ActiveRecord::Base
  include HotelHandler
  
  ...

end

自定义助手类:app/helpers/hotel_handler.rb

module HotelHandler
  ...
end

这给了我错误:

未初始化的常量 Hotel::HotelHandler (NameError)

【问题讨论】:

  • 如果你这样做include ::HotelHandler,它仍然会给你错误吗?
  • 是的,它仍然给我同样的错误
  • 你如何命名包含HotelHandler 的文件,你把它放在哪里?
  • 试试require_relative '../helpers/hotel_handler'
  • 如果它不是 Rails 项目,您可能没有设置自动加载器 (guides.rubyonrails.org/autoloading_and_reloading_constants.html),您需要为您的应用程序设置自动加载器(超出此问题的范围)

标签: ruby


【解决方案1】:

如果你想在一个普通的旧 Ruby 项目中设置 Rails 样式的自动和预加载,现代方法是使用Zeitwerk

# this file would be the "entry path" to your application such as config.ru

# loads an installs gems inline
require 'bundler/inline'

gemfile do
  source 'https://rubygems.org'
  gem 'zeitwerk'
end

root = Pathname.new(File.expand_path(__dir__))
env = ENV.fetch("MYAPP_ENV", 'development')
loader = Zeitwerk::Loader.new

# Mimics Rails by adding every subdirectory of `/app` and `/app/**/concerns` 
# as "root directories" where zeitwerk will find top level constants
paths = [
  dir[root.join('app/*/')]
  dir[root.join('app/**/concerns')]
].flatten.each do |path|
  loader.push_dir(path) if File.directory?(path)
end

# makes zeitwerk reload classes when they change
loader.enable_reloading if env == 'development'
loader.setup
# loads all classes on boot for performance
loader.eager_load if env == 'production'

这实际上只是一个快速而肮脏的最小示例,您通常会将这个逻辑封装到一个引导文件和一个“应用程序”类中。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-05-26
    • 2020-04-08
    • 1970-01-01
    • 2023-02-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-02-15
    相关资源
    最近更新 更多