BaseWithoutTable
BaseWithoutTable offers the power of ActiveRecord models, including validation, without having a table in the database. It can be handy in a number of situations, including
- behavior driven development
- constants management
- presentation layer
I'm using an older (svn) version but the current one is on github http://github.com/sofadesign/active_record_base_without_table/tree/master
Example
For example, my app keeps a bunch of choice lists that are reused in different forms. Eventually I'll implement CRUD operations for maintaining the lists, but for now its ok to hardcode the built-in ones.
class ChoiceList < ActiveRecord::BaseWithoutTable
column :project_id, :integer
column :name, :string
column :choices, :textarea
column :value_type, :string
def self.find( how )
choices = []
case how
when :all
choices << [new( :value_type => 'string', :name => 'Marital status', :choices => "Single\nMarried\nSeparated\nDivorced\nWidowed" )]
...etc...
Behavior Driven Development
As an alternative to mocking and stubbing of models that haven't been implemented, you can consider making a 'working mock' with BaseWithoutTable. For example, I had code that needed a model to respond to a #find call. Rather than mocking it, I actually implement it but without the database table. The find method returns an array of items to make the app function. Later I can go in and implement the model for real.
Constants Management
BaseWithoutTable is handy for any read-only data. Why experience the overhead of database access? And rather than just uninteligent Ruby constants, you get alot of the ActiveRecord goodies.
Presentation Layer
A presentation layer includes a virtual model and a corresponding controller that for example, aggregates multiple models for user interaction. Conventional Rails controllers and views can get kind of complicated doing this. There are a bunch of different solutions for presentation layers, some more formal than other (and lots of discussion) if you google for it. A simple way is to use BaseWithoutTable to make your virtual model, make a conventional controller for the model, along with its views. Then a form that has fields from various models can be read, write, and validated by the virtual model. (To be honest, I havent integrated this technique into my app but I'd like to soon).
Comments
>>
<p> This is a pretty cool plugin and I like the elegancy of the solution. </p><p> However, I noticed that git repo version doesn't seem to support AR::Base callbacks (e.g. after_save). I fixed the issue in my fork, which you're welcome to use: http://github.com/ratnikov/active_record_base_without_table/tree </p><p> I have also fixed the test suite to actually run, changed to use sqlite3 by default (rather than mysql), and added a gem spec.
New Comment