Initialize Static Data on Startup

Hi,

I want to initialize some variables once on startup with static data
from the db. The code is at the bottom. Here are all the scenarios I
tested:

  1. Call Setup.state_list inside environment.rb before the
    Rails::Initializer.run do |config| line. Then call the
    Setup.state_list from a controller.
  2. Call Setup.state_list inside environment.rb at the end of the file.
    Then call the Setup.state_list from a controller.
  3. Only call the Setup.state_list from a controller.
  4. Only call the Setup.state_list from a view helper - never in the
    controller.

Please not that I’ve tried this with Setup being a class or module. The
results from the scenarios are:

1 & 2) Every time I call the Setup.state_list from the controller it
will rebuild the list.
3) It will only initialize the variable the first time through.
4) Every time I call the Setup.state_list from the view helper it will
rebuild the list.

Great - so it appears that scenario 3 works. The problem is that this
isn’t done at startup. I don’t want the system to start if it can’t
initialize this and other information. Is something going on when I
call it from the environment.rb file that I’m not aware of? I know the
code could be written better, however, it does work. Does anyone have
any thoughts on how to do this?

Thanks in advance!

==========================
[i]
class Setup

What attributes do we have

@@state_list = nil

#################################

Public Section

#################################

def self.state_list
if @@state_list.nil? || @@state_list.size <= 0
RAILS_DEFAULT_LOGGER.debug(“init state now”)
self.init_state
end

RAILS_DEFAULT_LOGGER.debug("sending back stateList -

#{@@state_list.size}")
@@state_list
end

#################################

Private Section

#################################

private

def self.init_state
RAILS_DEFAULT_LOGGER.info(“Initializing state list”)
states = State.find( :all, :order => “country_id asc, label asc”)
@@state_list = []
if states.nil? || states.size <= 0
RAILS_DEFAULT_LOGGER.error(“Unable to load states for
initialization”)
# TODO
else
states.each { |s|
if @@state_list[s.country_id].nil?
@@state_list[s.country_id] = [s]
else
@@state_list[s.country_id].concat( [s] )
end
}
end
end
[/i]

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs