The goal is to initialize a class attribute using a class method that's overridden in sub-classes. Following is the definition of my ruby classes:
class A
class_attribute :query
self.query = self.generate_query
def self.generate_query
return "abcd"
end
end
class B < A
def self.generate_query
query_part_1 = "ab"
return query_part_1 + generate_query_part_2
end
def self.generate_query_part_2
return part_2
end
end
The reason I want to do this is because query is a constant string per class and should not be created again on instantiation but it's a complex string which is generated in multiple independent parts. Separating this logic out in methods would make the code cleaner. However, with this code, I get the undefined method generate_query for class A.
I have tried lazy initialization of the class attribute while instantiating the class like the following:
def initialize
query = self.class.get_query
end
def self.get_query
self.query = self.generate_query if self.query.nil?
end
However, this initializes the query to same value for both class A and B if A is instantiated first because self.query.nil? would then return false for B also.