【问题标题】:Rails Grape API include module - Zeitwerk::NameError - expected file to define constant, but didn't:Rails Grape API 包含模块 - Zeitwerk::NameError - 预期文件定义常量,但没有:
【发布时间】:2020-07-03 19:21:02
【问题描述】:

我想做一个小的代码重构并将客户端外部客户端从 gem 提取到一个单独的模块(它用于通过 gem 'dato' 连接到 DatoCMS API)。我的标准课程效果很好,如下所示:

app/services/receive_webhook/fetch_model_name.rb

module ReceiveWebhook
  class FetchModelName
    def initialize(model_id)
      @model_id = model_id
    end

    def call
      fetch_model(@model_id).dig('name')
    end

    private

    def client
      @client ||= Dato::Site::Client.new(Rails.application.credentials.datocms_api_token)
    end

    def fetch_model(model_id)
      client.item_types.find(model_id)
    end
  end
end

我想将 client 方法分离到不同的模块中,并将其包含在 FetchModelName 类中(就像在标准 Rails 应用程序中一样)。为此,我使用以下代码:

app/dato_cms_api/dato_client.rb

module DatoCmsApi
  module DatoClient
    def client
      @client ||= Dato::Site::Client.new(Rails.application.credentials.datocms_api_token)
    end
  end
end

更新FetchModelName 类: app/services/receive_webhook/fetch_model_name.rb

module ReceiveWebhook
  class FetchModelName
    include ::DatoClient

    def initialize(model_id)
      @model_id = model_id
    end

    def call
      fetch_model(@model_id).dig('name')
    end

    private

    def fetch_model(model_id)
      client.item_types.find(model_id)
    end
  end
end

但我收到一个错误:

Zeitwerk::NameError - expected file app/dato_cms_api/dato_client.rb to define constant DatoClient, but didn't:
  app/services/receive_webhook/fetch_model_name.rb:5:in `<class:FetchModelName>'
  app/services/receive_webhook/fetch_model_name.rb:4:in `<module:ReceiveWebhook>'
  app/services/receive_webhook/fetch_model_name.rb:3:in `<main>'
  app/controllers/api/v1/webhooks/dato_cms/receive_webhook.rb:29:in `block in <class:ReceiveWebhook>'

Grape API 不支持包含模块实践吗?

【问题讨论】:

  • 恐怕您在使用 include 时错过了顶级模块。似乎您需要尝试定义include ::DatoCmsApi::DatoClient
  • naah,忘了添加这个,但是::DatoCmsApi::DatoClient 我有一个错误&gt; uninitialized constant DatoCmsApi Did you mean? DatoClient
  • 啊,明白了。只需删除module DatoCmsApi,一切都会完美运行。
  • 但这与FetchModelName 类位于不同的文件夹中。它在app/dato_cms_api/... 中,所以这个名为dato_cms_api 的文件夹不应该反映在模块中?
  • 应用目录中的任何新文件夹/目录都不被视为模块。之后,如果您需要目录中的目录,则需要将其视为模块。

标签: ruby-on-rails ruby grape grape-api


【解决方案1】:

您是否尝试将自动加载器降级为经典? 在您的 application.rb 文件中,添加以下内容:

config.autoloader = :classic

【讨论】:

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