Public Model Objects -or- Public ActiveRecord Objects
Sometimes you just need a “global” or “public” object that contains data. If you store your “application settings” or “company configuration” information in a database table (which I like to do), then it makes sense that you could use ActiveRecord like you would for any other table, just in a global context.
This would allow you to easily read and update the information. It also neatly puts it in a single object instead of spreading it out across a bunch of individual public variables. Yes, you could dump it in the Session or use an excellent plug-in like AppConfig, but if you have several application-wide groups of data like “application settings” and “company configuration”, they end up all together in one object model (I think).
For simplicity, let’s say I have a table named app_settings that stores a bunch of application-wide settings. To get a public/global model/activerecord object, I would do the following:
Create a standard Model (\app\models\appsetting.rb)
class AppSetting < ActiveRecord::Base
end
Create a standard Controller (\app\controllers\appsettings_controller.rb)
class AppSettings_ Controller < ApplicationController
def index
list
render :action => ‘list’
end
def list
@ appsettings = AppSetting .find( 1 )
end
def show
@ appsettings = AppSetting .find(params[ : id ])
end
end
Add code to application.rb (\app\controllers\application.rb)
#If $AppSetting object is empty or does not exist, create it now.
begin
if $ AppSetting .nil?
$ AppSetting = AppSetting .find( 1 )
end
rescue
$ AppSetting = AppSetting .find( 1 )
end
Add ”AppSettings” to your Views:
Application Name : <% = $ AppSetting . AppLongName %>
Version : <% = $ AppSetting . AppVersion %>
*Don’t forget to restart your application server after modifying application.rb (ruby script/server)
*Don’t forget that the names of these models, controllers, and fields are case-sensitive.