简体   繁体   中英

how do I execute ruby code with access to the Database before rails application begins?

I will like to know how can I execute some ruby code just before the rails application begins. I need to have access to database and be able to set some variables for the views to access.

Thanks.

I think, a better approach is to not go with database, but create a configuration file, say, app_config.yml in your application_root/config folder, and then load it using the following line in the environment.rb file.

APP_SETTINGS = YAML.load_file("#{Rails.root.to_s}/config/app_config.yml")

Your app_config.yml file looks like this

appname: something.com
appsettings: something...
appvar: something...

You can access these config variables from anywhere in your application as:

APP_SETTINGS['appname']

and so on.

This yml file is loaded at the time the rails server is started. Hence, if you make any changes to this file, your server should be restarted.

If you want to set up something that the views can use right away, try sticking the code in db/seeds.rb . That's where you should put any creation of objects that you might need, like reference data (eg populate a Countries table or set up some user Roles).

It is automatically run when the DB is reset, or through rake db:reset .

Use activerecord alone to set some constants.

http://weblog.jamisbuck.org/2005/10/3/easy-activerecord-scripts

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM