简体   繁体   中英

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!

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.

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

This way both will run, if super is anything except nil or false

Alternatively, you can use the stronger precedenced && but this lower precedence is often used as flow control.

See Avdi's blog post about this.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM