2012-04-01 5 views
4

Ich habe eine FUU Constante innerhalb Foo und Foo2 Klassen, und um meinen Code zu trocknen, habe ich eine Methode innerhalb der BaseStuff Superklasse verschoben. Genau wie folgt aus:Nicht initialisierte Konstante aus der Oberklasse

class BaseStuff 
    def to_s 
    FUU 
    end 
end 

class Foo < BaseStuff 
    FUU = "ok" 
end 

class Foo2 < BaseStuff 
    FUU = "ok2" 
end 

Aber mein Problem ist, dass nach:

a = Foo.new 
puts a.to_s 

ich diesen Fehler:

NameError: uninitialized constant BaseStuff::FUU

Gibt es eine bewährte Methode, um dieses Problem beheben?

Antwort

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

Einfach perfekt. Vielen Dank! – Doug

3
class Foo < BaseStuff 
    ::FUU = "ok" 
end 
+0

Waw, funktioniert gut! In meinem Fall kann das jedoch schwierig sein, weil ich diese Konstante dynamisch hinzufüge. Danke trotzdem. – Doug