Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby class method inheritance, how to stop the child method from executing?

This question pertains to a Ruby on Rails problem but this simplified problem will give me the solution I am looking for.

I have two classes, the child class is inheriting a parent method, but I want to half the execution of the child method code if certain conditions are met in the parent method.

class A

  def test_method
    puts 'method1'
    return false
  end

end

class B < A

  def test_method
    super
    #return false was called in parent method, I want code to stop executing here
    puts 'method2'
  end

end

b = B.new
b.test_method

And the output is:

method1
method2

My desired output is:

method1

Does anyone know how to achieve my desired output?

Thanks!

like image 839
MichaelHajuddah Avatar asked Oct 18 '25 15:10

MichaelHajuddah


1 Answers

You could use simple if-end statement:

class B < A
  def test_method
    if super
      puts 'method2'
    end
  end
end

Now, B#test_method will return false if super returns false. Otherwise it evaluates code inside if-end block.

like image 108
Marek Lipka Avatar answered Oct 21 '25 06:10

Marek Lipka