Search code examples
ruby-on-railsrubyclassstatic-methodsstatic-variables

How to call a method to load class variable in Ruby?


The data is loaded once because it takes a while to load, doesn't change, and is shared. This is a static class: I am not using any instances.

class Foo
  @@ data = self.load_data

  def self.load_data
    .
    . 
    .
  end

  def self.calculate
    .
    .
  end
end

This throws an error NoMethodError: undefined method 'load_data' for Foo:Class because load_data appears after the assignment.

I don't think initialize will work because I am not using f = Foo.new. I am using it as Foo.calculate.

Is it necessary to declare load_data before calling it? Or is there a better approach?


Solution

  • Yes Foo.load_data doesn't exist yet at the point you call it.

    A better pattern might be to have an accessor for @@data which auto-memoizes.

    class Foo
      def self.data
        @@data ||= load_data
      end
      def data; self.class.data; end # if you need it in instances too
    
      def self.load_data
        ...
      end
    
      def self.calculate
        data.each {} # or whatever would have used @@data
      end
    end