Austin L Austin L - 6 months ago 36
Ruby Question

Ruby: Calling gem subclass within module produces uninitialized constant

I have 2 projects, a "common code" project that i have made into a big module that pulls in other modules like so:

Here is the folder structure of "my-common-project":


  • my-common-project


    • common


      • rest-client.rb

      • other ruby files with modules...


    • common.rb

    • Gemfile

    • etc...




common.rb



require 'bundler'
Bundler.require
require_relative './common/rest_client.rb'
...

module Common
include RestClient
# include other modules here...


rest-client.rb



module Common
module RestClient

def call_rest_service_get(url)
begin
response = RestClient.get(url, {accept: :json})
rescue RestClient::Exception => err
return err.response
else
return response
end
end
end


Gemfile



# frozen_string_literal: true
source 'https://rubygems.org'

gem 'rest-client'
# other gems here...


Then in another project called "my-other-project":


  • my-other-project


    • service


      • service.rb





service.rb



require_relative './../../../common/common.rb'

class Service

include Common

def get_rest_data
call_rest_service_get('http://some-url.com)
end
end


I get an Error when the code makes it to the rescue block in rest-client.rb:

NameError - uninitialized constant Common::RestClient::Exception


I'm not sure how to phrase my question, but somewhere along the line it seems the common module is losing out on the rest client modules other classes, in this example Exception. Can someone explain why this method of lumping and then including many modules isn't working?

Answer Source

Since you have a class called Common::RestClient and are using a ruby gem which defines a class RestClient, when you're within your Common module, you'll need to reference the gems RestClient with a :: prefix, otherwise, it assumes you're talking about Common::RestClient

module Common
  module RestClient

  def call_rest_service_get(url)
    begin
      response = ::RestClient.get(url, {accept: :json})
    rescue ::RestClient::Exception => err
      return err.response
    else
      return response
    end
  end
end
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download