Home > Software design >  Override part of the inherited controller method in Rails
Override part of the inherited controller method in Rails

Time:12-14

i have a method in the first class

 class1
   def method(param_test)
     if !organization.empty?
       organization = test(param_test)
     end
    end
  end

Class 2 inherits from Class 1

class2  < class1

end

I would like to modify the line organization = test(param_test)

without having to copy the whole method in the class2

it's possible?

CodePudding user response:

I would separate the logic into two methods like this:

# in the parent class
def method(param_test)
  if !organization.empty?
    organization = fallback(param_test)
  end
end

def fallback(param)
  test(param)
end

And then just override the one method in the child class like this:

# in the child class
def fallback(param)
  # logic to return the expected response
end

An alternative might be to change the test method in the subclass. But how that might look like depends on the specific use case and the internals of the test method.

CodePudding user response:

You can use the super keyword in class2 to call the method in class1, and then override the line that you want to change:

class2 < class1
  def method(param_test)
    super
    organization = different_test(param_test)
  end
end

In this example, the method in class1 will be called, but the line organization = test(param_test) will be overridden with organization = different_test(param_test) in class2.

  • Related