December 31, 2007

Public Models (oh myyyyy)

Filed under: model, public, rails, ruby — oomoo @ 8:53 pm
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

Create a standard Controller (\app\controllers\appsettings_controller.rb)
class AppSettings_ Controller < ApplicationController
  def index
:action => ‘list’
  def list
    @ appsettings = AppSetting .find( 1 )
    @ appsettings = AppSetting .find(params[ : id ])


Add code to application.rb (\app\controllers\application.rb)

#If $AppSetting object is empty or does not exist, create it now.
$ AppSetting .nil?
    $ AppSetting = AppSetting .find( 1 )
  $ AppSetting = AppSetting .find( 1 )


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.


Leave a Comment »

No comments yet.

RSS feed for comments on this post. TrackBack URI

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

Create a free website or blog at WordPress.com.

%d bloggers like this: