RubyRedGrapefruit
RubyRedGrapefruit

Reputation: 12224

How can I cache the contents of a text file in a model once per deployment?

I have this text file in which I have to refer to values inside it constantly. I must compare certain values from the database against certain entries in the text file. Both datasets are very large. I do not load this text file (I'll call it the changefile) into the database, because doing the comparisons in the database takes way too long. And I don't put the changefile into a database table, because it's easier to read from a file, and I don't want to have to search for an upload a new changefile every time a new one is released.

What I do instead is read a bunch of records from the db into text strings, read the file into text strings, and compare those.

I have a model in which the text strings from the changefile are represented in a variable. It looks like this:

class Standard < ActiveRecord::Base

  def changes
    @changes ||= read_the_file_into_an_array
  end

end

This is good because I am only doing the file read once. However, that's once per instantiation of the Standard class. What I want to do is ensure that I only read the file once per deployment.

Outside of reading the file into some kind of ugly global variable in an initializer, what can I do to make sure I only ever read the file once after Rails boots up?

* UPDATE *

class MyObject < ParentObject

  @changes ||= get_changes

  class << self

    attr_accessor :changes, :get_changes

    def get_changes
      <read file and return array>
    end

  end

end

Can't get this working. Error:

NameError: undefined local variable or method `get_changes' for MyObject:Class

I don't get it at all. Why is get_changes being accessed as a local variable?

Upvotes: 0

Views: 102

Answers (1)

lsaffie
lsaffie

Reputation: 1814

make it be read as part of an initializer and load it into a variable or config depending on the file context

Upvotes: 1

Related Questions