Home > other >  Ruby including Errors module in another module - uninitialized constant Errors
Ruby including Errors module in another module - uninitialized constant Errors

Time:10-06

I've got NON-RAILS app where I want to include Errors module to Formatter module to access the method error_class from Errors. Like below:

#lib/formatter.rb
    module Formatter
      module_function
    
      include ::Errors
    
      def format(number)
        number.delete!(' ')
    
        raise error_class(:invalid_number), 'Invalid phone number, check your entries' unless valid?(number)
      end
    end

#lib/errors.rb

module Errors
  class FormatterExceptionError < StandardError; end

  PhoneNumberInvalid = Class.new(FormatterExceptionError)

  def error_class(status)
    case status
    when :invalid_number
      PhoneNumberInvalid
    end
  end
end

With this code I'm getting an error:

Failure/Error: include ::Errors NameError: uninitialized constant Errors Did you mean? Errno

CodePudding user response:

Non-rails apps doesn't have auto-load classes, so you need to manually require it. Also one thing of your code, I don't know why you are using :: before constant, I don't see any naming-confusion in order to use it. It is used only when you have your Errors modules on different namespace, and you need to resolve the one from your namespace.

# lib_formatter
require 'errors'

module Formatter
  extend Errors
  # ...
end

The second issue with your code, that you have defined instance method, but where you include your code there class method (module method)

So errors class should be adjusted to

module Errors
  # ...
  module_function
  # ...
end

The third issue is include/extend misusage.

Include used to make all methods from module you using to become instance methods.
Extend used to make all methods from module you using to become class methods.

include/extend info

  •  Tags:  
  • ruby
  • Related