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?

2 Answers 2

3
class Foo < BaseStuff
  ::FUU = "ok"
end
1
  • Waw, works well! However this may be tricky to use in my case, 'cause I'm adding this constant dynamically. Thanks anyway.
    – T5i
    Apr 1, 2012 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
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.