Home > Software design >  Call a method from an another class in Ruby (API rails)?
Call a method from an another class in Ruby (API rails)?

Time:06-08

The question can be stupid, but I always develop in C# and now I need to develop in Ruby. And I don't really understand how to call a method from an another class. I mean, I've this structure :

- model
   |_________ my_model.rb
   |_________ helper
                |____ my_helper_class

my_model.rb

   def self.create_new_ticket(member_to_update)
    # I want to call here my_helper_class
    MyHelperClass.generate_guid
   end

my_helper_class :

class MyHelperClass
 
def generate_guid
  return "So haaard"
end

end 

And I don't have access to my method named generate_guid from my other class. I've this type of error :

uninitialized constant

I would like to have an access with a static class or whatever. The initilize method doesn't work too (given argument problem ??)

So I think I understand bad something with Ruby and the manipulation of objects because of my habits in C#.

Can you help me please ? With some good documentations or an example here ?

Thanks a lot guys.

CodePudding user response:

I think your error is straightforward. Your generate_guid is not a static method or class method. You have to put self in front of it in the definition which will make it a class method.

Another important thing to notice is you have created /helper folder inside /model so you have to implement helper class inside a module named Helper which should be same as folder name.

Helper class should be

module Helper
 class MyHelperClass
 
  def self.generate_guid
    return "So haaard"
  end
    /* 
    an alternate way to define class methods would be 

    class << self 
      def generate_guid
        "So haaard"
      end
     
      def some_other_class_method
         "some thing"
      end  
    end 
   */
  end 
end 

So, whenever you have to call static method you have to call it with full scope like Helper::MyHelperClass.generate_guid

  • Related