用于游戏化的未定义方法"hello"::用户:模块



我在app/models/user.rb:中有一个类

class User
  include Gamification::User
  def self.hello
    puts "hello"
  end
end

我在lib/gamification/user.rb:中有一个模块

module Gamification
  module User
    extend ActiveSupport::Concern
    module ClassMethods
    end
  end
end

我有另一个模型ap/models/conversation.rb

class Conversation
    def hello
      User.hello
    end
end

config/application.rb:

config.autoload_paths += Dir["#{config.root}/app/models/**/"]
config.autoload_paths += Dir["#{config.root}/lib/**/"]
config.autoload_paths += Dir["#{config.root}/app/models/tracker_related/**/"]
config.autoload_paths += Dir["#{config.root}/app/helpers/**/"]
config.autoload_paths += Dir["#{config.root}/app/models/concerns/**/"]

当我点击Conversation.new.hello时,我希望它应该打印"hello"。但它回来了:

undefined method `hello' for Gamification::User:Module.

我在这里做错了什么?

问题是将lib文件夹中的所有文件夹添加到自动加载路径中。当rails第一次达到User常量时,它会在检查默认路径(如app/models)之前,先检查这些文件夹中名为user.rb的文件。由于存在这样的文件,它会返回其中定义的类/模块

我不认为以这种方式添加文件夹是最佳做法(由于这个问题)。尝试删除

config.autoload_paths += Dir["#{config.root}/lib/**/"]

并放置

config.autoload_paths << "#{config.root}/lib/"

但是,这将强制您使用完全限定的常量名称,如Gamification::User,而不是User

相关内容

最新更新