Alexandre
Alexandre

Reputation: 13318

Unable to override base class method in derived class

Here are the Ruby classes I have:

class MyBase
  class << self
     def static_method1
        @@method1_var ||= "I'm a  base static method1"
     end

     def static_method1=(value)
        @@method1_var = value
     end

     def static_method2
        @@method2_var ||= "I'm a base static method2"
     end

     def static_method2=(value)
        @@method2_var = value
     end
  end

  def method3
    MyBase::static_method1
  end
end

class MyChild1 < MyBase
end

class MyChild2 < MyBase
  class << self
     def static_method1
        @@method1_var ||= "I'm a child static method1"
     end
  end
end

c1 = MyChild1.new
puts c1.method3 #"I'm a  base static method1" - correct


c2 = MyChild2.new
puts c2.method3  # "I'm a  base static method1" - incorrect. I want to get "I'm a child static method1"

I'm aware of attr_accessor and modules, but I can't use use them here because I want them to give default values in MyBase class. I want to override MyBase.static_method1 in MyChild2.

Upvotes: 0

Views: 414

Answers (1)

Daniel Evans
Daniel Evans

Reputation: 6818

The problem is that method3 is always explicitly calling the method on the base class. Change it to this:

def method3
  self.class.static_method1
end

After that, consider not using @@.

@@ in ruby is extremely counterintuitive and rarely means what you think it means.

The problem with @@ is that it is shared across the all of the inherited classes and the base class. See this blog post for an explanation.

Upvotes: 2

Related Questions