Home > Software engineering >  How to call a methods in multiple classes in ruby
How to call a methods in multiple classes in ruby

Time:04-11

class One 
  class Two
    class Three 
      def name
        Faker::Name.name
      end 
    end 

    def workflow
      Three.new
    end
  end

  def event
    Two.new
  end

  def id
    Faker::Number.number(4).to_i
  end 
end

I am new to ruby. Can someone help me, how to call all these methods in ruby?

CodePudding user response:

Is this what you looking for?

one = One.new
two = One::Two.new
three = One::Two::Three.new

three.name
# => "Mr. Dillon Jacobson" 

two.workflow
# => #<One::Two::Three:0x000055b2d9d70be0>

one.event
# => #<One::Two:0x000055b2df4160d0>
one.id
# => 6579413068

CodePudding user response:

Pretty simple to do with instance_methods(false) that will give us all the defined instance methods of a class. We can then just push all the nested objs into an array and iterate over them. I'm not too sure on how to get all nested classes. You can however do that with Module.nesting

def call_all_methods(obj)
  obj.class.instance_methods(false).each do |m|
    obj.public_send(m)
  end
end

[
  One.new,
  One::Two.new,
  One::Two::Three.new
].each do |obj|
call_all_methods(obj)
end
  • Related