0

I have

/a.rb

require_relative ‘a/b’
module A
  def self.foo
    "HA"
  end
end

/a/b.rb
module A
  class B
    VAR = A.foo * 3
  end
end

Unfortunately it errors out as Undefined foo method inside A module and I don't know why. A is used mostly as a namespace, and I've decided to put some methods in there as configuration - they actually set the root of the project and the root + /config directory for configuration purposes.

How can I accomplish this?

1
  • I can't reproduce the problem with the code given. Are you sure you're declaring them in this order? Commented Feb 15, 2019 at 17:40

2 Answers 2

2

Sounds like there's more to this story. The code you've given as an example works as-is, without errors:

$ irb
2.5.1 :001 > module A
2.5.1 :002?>     def self.foo
2.5.1 :003?>         "HA"
2.5.1 :004?>       end
2.5.1 :005?>   end
 => :foo 
2.5.1 :006 > 
2.5.1 :007 > module A
2.5.1 :008?>     class B
2.5.1 :009?>         VAR = A.foo * 3
2.5.1 :010?>       end
2.5.1 :011?>   end
 => "HAHAHA" 
2.5.1 :012 > A.foo
 => "HA"

If your code is arranged across multiple files as you've alluded to, the cause of the problem is most likely to be how those files interact with each other. However, without more information, I can't debug that.


You've since edited the file structure in, so the problem has become clear. Your require_relative call in a.rb comes before you define module A and A.foo - that means the code in a/b.rb runs before the code in a.rb, so A.foo really isn't defined at the point you're trying to call it.

Sign up to request clarification or add additional context in comments.

2 Comments

Updated the snippet with the file structure
Oh and I have a test on A.foo that works as expected, problem is when I then use it in the separate class
0

Problem was requiring the file before defining the methods I was using in it. I was requiring b.rb before defining A::foo.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.