Reputation: 521
Is there a simple way to initialize a class variable through a class method in Ruby? I'm trying this:
class MyClass
@@product_families = MyClass.load_pgrollups(File.join(File.dirname(__FILE__), ASSETS_FOLDER_NAME, PGROLLUP_CSV_FILENAME))
def self.load_pgrollups(csv_file)
....
return product_families
end
I'm getting an exception: undefined method `load_pgrollups' for ModuleName::myClass:Class
I don't necessarily want to initialize a class variable. I also tried to initialized a constant in a module through a module function
module ModuleName
PRODUCT_FAMILIES = load_pgrollups(File.join(File.dirname(__FILE__), ASSETS_FOLDER_NAME, PGROLLUP_CSV_FILENAME))
def load_pgrollups(csv_file)
....
return product_families
end
but I got undefined method `load_pgrollups' for MyModule:Module
Upvotes: 2
Views: 770
Reputation: 369458
You define the method in line 4, but you are already calling it in line 2, where it hasn't been defined yet. So, yes, the method is undefined at the point you are calling it.
Upvotes: 2
Reputation: 168101
Call it after it is defined:
class myClass
def self.load_pgrollups(csv_file)
....
return product_families
end
@@product_families = load_pgrollups(File.join(__dir__, ASSETS_FOLDER_NAME, PGROLLUP_CSV_FILENAME))
end
Upvotes: 5