4

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?

T5i
  • 1,470
  • 1
  • 18
  • 34

2 Answers2

3
class Foo < BaseStuff
  ::FUU = "ok"
end
mikdiet
  • 9,859
  • 8
  • 59
  • 68
  • Waw, works well! However this may be tricky to use in my case, 'cause I'm adding this constant dynamically. Thanks anyway. – T5i Apr 01 '12 at 16:50
2
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
evfwcqcg
  • 15,755
  • 15
  • 55
  • 72