Reputation: 1282
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?
Upvotes: 0
Views: 48
Reputation: 1282
Problem was requiring the file before defining the methods I was using in it.
I was requiring b.rb
before defining A::foo
.
Upvotes: 0
Reputation: 406
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.
Upvotes: 2