0

I have these 2 files in a large system, both are located in PackA

  1. people.rb
module People
  class HobbyValueObject
  end
end
  1. job.rb
module People
  class Job
  end

  class CityValueObject
  end
end

I am trying to use CityValueObject in a different module like this,

Module is in PackB

  1. work.rb
module Profile
   class Work
       ....
       def calculateTaxes
          ...
          a = People::CityValueObject....
       end
   end
end

But it's giving me an error saying,

NameError: uninitialized constant People::CityValueObject

Did you mean? People::HobbyValueObject

Why is not being able to fine CityValueObject but can find HobbyValueObject just fine? How do I make it find the object that I am intending to use?

I am not explicitly declaring any requires or includes

Quick-gun Morgan
  • 338
  • 12
  • 31
  • 3
    Is it possible that the one file was already required and loaded, but the other file was not? Where are the files located, and what are they named? Hint: Rails autoloading only works when files and the classes inside those files follow certain naming conventions. – spickermann Feb 08 '23 at 17:25
  • I edited the question with those details. I think you might be right about how autoloading only works with certain naming conventions. I might have to explicitly import the file I am trying to use. – Quick-gun Morgan Feb 08 '23 at 17:33
  • 2
    Do you really need to define CityValueObject in `job.rb`? The easiest solution is to just move it into its own file. Alternatively you can just "fool" the autoloader by referencing `People::Job` first. – max Feb 08 '23 at 17:36
  • I do not have the ownership over People module so I can only work within how I can import the class that I need. – Quick-gun Morgan Feb 08 '23 at 21:20
  • What do you mean by "PackA" and "PackB"? Are those directories or maybe gems? How are these files being loaded? Do you rely on Rails' autoloading or do you load / require them explicitly? – Stefan Feb 09 '23 at 07:51

1 Answers1

0

I was able to resolve this by adding require at the top while using full path file name.

require './packs/people/app/public/people/job'
Quick-gun Morgan
  • 338
  • 12
  • 31
  • Using `.` in a `require` statement is pretty brittle. `require_relative` is better. See https://stackoverflow.com/a/9750732/28128 – David Grayson Feb 08 '23 at 21:32