Question

I have a FUU constante inside Foo and Foo2 classes, and in order to DRY my code, I moved a method inside the BaseStuff superclass. Just like this:

class BaseStuff
  def to_s
    FUU
  end
end

class Foo < BaseStuff
  FUU = "ok"
end

class Foo2 < BaseStuff
  FUU = "ok2"
end

But my problem is that, after:

a = Foo.new
puts a.to_s

I get this error:

NameError: uninitialized constant BaseStuff::FUU

Is there a best practice to fix this?

Was it helpful?

Solution

class BaseStuff
  FUU = nil
  def to_s
    self.class::FUU
  end
end

class Foo < BaseStuff
  FUU = "ok"
end

class Foo2 < BaseStuff
  FUU = "ok2"
end

a = Foo.new
puts a.to_s # => ok

puts Foo2.new.to_s # => ok2

OTHER TIPS

class Foo < BaseStuff
  ::FUU = "ok"
end
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top