I have a problem. I am new to Ruby, so I am struggling with some issues, which I can resolve after a couple hours, but this one is bugging me for a day now.
I created a class in /lib/math/calc.rb
with the following content:
module Math
module Calc
class << self
def check!(value1: nil, value2: nil)
raise Error.new(message: "value1 is required") unless value1
raise Error.new(message: "value2 is required") unless value2
Divide.send!(value1: :value1, value2: :value2)
end
end
end
end
Then I also have a class Divide
which is located in: /lib/math/calc/divide.rb
, with the content:
module Math
module Calc
class Divide
class << self
def send!(value1: nill, value2: nill)
# More code here
end
end
end
end
end
Now when I call: Math::Calc.check!(5, 5)
, I get the following error:
NameError: uninitialized constant Math::Calc::Divide
I already tried inserting require 'divide'
, but those imports do not exist he said.
What am I doing wrong here?
CodePudding user response:
If you wanna do it using plain Ruby you just need to require the Divide
file inside of your module, so the intepreter knows where the file is located
File tree:
- lib/math/calc.rb
- lib/math/calc/divide.rb
# lib/math/calc.rb
require_relative 'calc/divide'
module Math
module Calc
class << self
def check!(value1: nil, value2: nil)
raise Error.new(message: "value1 is required") unless value1
raise Error.new(message: "value2 is required") unless value2
Divide.send!(value1: :value1, value2: :value2)
end
end
end
end
Aside from that: note that you don't have the Error
class defined in there. You also are not actually sending the proper values to Divide.send!
. In order to do it you should send Divide.send!(value1: value1, value2: value2)
CodePudding user response:
Maybe try the below.
lib/math/calc.rb
module Math
module Calc
require_relative './calc/divide'
extend self
def check!(value1: nil, value2: nil)
raise Error.new(message: "value1 is required") unless value1
raise Error.new(message: "value2 is required") unless value2
Divide.send!(value1: :value1, value2: :value2)
end
end
end
lib/math/calc/divide.rb
module Math
module Calc
class Divide
def self.send!(value1: nill, value2: nill)
# More code here
end
end
end
end
Also, maybe create your lib directory inside your app e.g app/lib