I am new to Ruby and was trying out my first few programs in Ruby to understand the concepts. Now, in Class Method concept while trying out the basics I came across the following problem.
I have a Class method "Servers.valid_requestor".
This is supposed to check if the supplied username is valid one based on a pre-defined username I'm using and if yes it should execute certain piece of code in main.
Now the issue here is whenever I try to get the username by using myInput.user_name it returns Undefined method user_name for the my_input object (NoMethodError)
in `validRequestor': undefined method `user_name' for #Object (NoMethodError)
class Servers
# Constructor
def initialize(user_name, ip_address, host_name)
@user_name = user_name
@ip_address = ip_address
@host_name = host_name
end
# Class Method
def Servers.valid_requestor(my_input)
user_name = my_input.user_name
return user_name.to_s == "myUserName"
end
# Member function
def print
puts "I am in super"
my_details = "Details: #{@user_name} -- #{@ip_address} -- #{@host_name}"
end
end
# MAIN
a_server = Servers.new("myUserName", "10.20.30.40", "server1.mydomain.private")
if (Servers.valid_requestor(a_server))
my_details = a_server.print
puts my_details
<do something>
end
If I add a method as below in Servers class, the issue resolves as I believe myInput.userName looks for a method.
def user_name
@user_name
end
But can I get some pointer on why I need to have this method. I am trying to understand how exactly this work internally when you call something like my_input.user_name
I tried to get some documentation in detail on Class methods but in most cases those are explained with very simple example like some puts statements. If anyone can explain Class Method and accessing variables, objects etc inside a class method it would be really helpful. I have seen answers similar to one mentioned in "undefined method" error ruby , that gives me the idea to resolve the issue, but I needed a bit more details on how it internally works. Any pointer will be helpful.