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 开发者_JAVA技巧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.
Use activerecord alone to set some constants.
http://weblog.jamisbuck.org/2005/10/3/easy-activerecord-scripts
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 (e.g populate a Countries table or set up some user Roles).
It is automatically run when the DB is reset, or through rake db:reset
.
精彩评论