2

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?

2 Answers 2

2

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
Sign up to request clarification or add additional context in comments.

Comments

0

Load data by class level function call.

class Foo
  def self.load_data
    .
    . 
    .
    @data = value
  end

  def self.calculate
   #use @data in this function.
   .
   .
  end
end

#first load data
Foo.load_data

#then process data
Foo.calculate

2 Comments

Foo.calculate is run through a cron job, so there is no good time to call load_data. In this case it's better to auto-load somehow...
then call load_data from calculate method.

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.