Sasanka Panguluri
Sasanka Panguluri

Reputation: 3138

Rails - including module containing a class gives Uninitialized Constant error

My application has lib/project/errors which contains a bunch of Exception classes, one of which is ServiceException

module Project
  module Errors
    class ServiceException < Exception

      def initialize(message = nil)
        super message
      end
    end
  end
end

I am trying to use this in my GameService:

module GameMan


  class GameService
     Blah blah

     def validate(score)
       raise Project::Errors::ServiceException.new('blah')
     end

  end
end

This works, however I hate writing the full module path everywhere. Is there a way to avoid this?

I have tried

module GameMan

   class GameService
      include Project::Errors
      Blah blah

      def validate(score)
       raise ServiceException.new('blah')
      end

    end
end

This gives uninitialized constant ServiceException error.

I have config.autoload_paths += %W(#{config.root}/lib #{config.root}/app/services) already set inapplication.rb``

What am I doing wrong?

Upvotes: 0

Views: 424

Answers (2)

Rajnik
Rajnik

Reputation: 83

include Project::Errors

Replace above line to following line include Project::Errors::ServiceException

Upvotes: 0

Andrey Deineko
Andrey Deineko

Reputation: 52377

It is all about constants lookup.

ServiceException is defined in the scope of Project::Errors. When you reference ServiceException without prefixing Project::Errors it looks for the class defined in the outer scope, and failing, because there is none.

You should be using the full path.

Upvotes: 1

Related Questions