Simple Stuff In Rails: You don’t have to use the database for everything!

Sometimes I find myself creating database tables for something that doesn’t really need to be in a database at all. Think configuration. Say you build a CMS or a blog system of some sort, and then you want some simple data to be accessible without putting in a database. You don’t need all that over head for everything!

So, what to do? This is part of the Mystery of Rails Models! Just create a model.
script/generate model Site
In app/models/site.rb you can do a lot of convenient things by just defining methods. An example:

class Site < ActiveRecord::Base

def self.name
"Goodbye Helicopter"
end

end

(I know, I know. This is a WordPress site. ignore the man behind the curtain!)
Then, in your .rhtml view files, you can simply call that method at any time you choose!
Like this:

<%= Site.name %>

And the result will be the return value of the method called!

Clearly, this is a very extensible way to do things. You can set a whole bunch of easy to call and reuse variables this way. These methods use ActiveRecord but not a database. However, if you do have an application that you want to deploy to multiple places as different, configurable sites, you could also use a YAML file to hold more configuration info and then load it at the beginning of the model file. If you really want to set and forget it, you could make it part of a Rake task, in a setup script for the site that asks a first time user to set the data for configuring a site.

The beauty of this, is that it will make sense to Rubyists who are used to Ruby but new to Rails. Those are also the people most likely to abuse it as well :)

Now, a caveat: I don’t know how well this scales for various solutions, but at least it cracks a window for you on the power of what you can do with Rails’ models!

0 comments ↓

There are no comments yet...Kick things off by filling out the form below.

Leave a Comment