0
votes

I want to make a small code refactor and extract client external client from gem to a separate module (it's use to connect to the DatoCMS API via gem 'dato'). My standard class, which works well, look like:

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

I want to separate client method to a different module and include it in FetchModelName class (like in standard Rails app). To do so I use below code:

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

With updated FetchModelName class: 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

But I'm getting an error:

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>'

Does Grape API not support include module practice?

1
I am afraid if you have missed top level module while using include. Seems like you need to try defining include ::DatoCmsApi::DatoClientTashi Dendup
naah, forgot to add this but with ::DatoCmsApi::DatoClient I've got an error > uninitialized constant DatoCmsApi Did you mean? DatoClientmr_muscle
Ahh, got it then. Just remove module DatoCmsApi and every thing should work perfectly.Tashi Dendup
But this is in a different folder than FetchModelName class. It's in app/dato_cms_api/... so this folder called dato_cms_api shouldn't be reflected in module?mr_muscle
Any new folder/directory inside app directory is not considered as module. After that if you need directory inside directory, then you need to consider it as module.Tashi Dendup

1 Answers

0
votes

Did you try to downgrade your autoloader to classic? In your application.rb file, add this:

config.autoloader = :classic