Helpful for creating lookup-table-like rails models
Ruby
Latest commit 7fac848 Jul 31, 2012 @crx crx check for existence of attribute setter in
acts_as_lookup_write_missing_values

README.rdoc

acts_as_lookup

Overview

Provides an easy means for creating models that act like enumerations or lookup tables. You can specify the lookup values in your Rails models and can lazily push these to the associated db tables (or not). Also dynamically adds helpful class-level methods to access singleton instances of each value in your lookup

What to do

Rails models

Defining a lookup model

In your model, do something like:

def MyLookup < ActiveRecord::Base
  VALS = [ { :id => 1, :name => "value 1", ... other attributes },
           { :id => 2, :name => "value 2", ... other attributes },
           ... other lookup values ...
         ]
  acts_as_lookup :values => VALS, ... other options ...
end

Associating a model with a lookup model

In your model, you can specify an association to a lookup using has_lookup:

def MyModel < ActiveRecord::Base
  has_lookup :my_lookup
end

Alternatively, you can explicitly state the class name of the associated lookup:

def MyModel < ActiveRecord::Base
  has_lookup :my_association, :class_name => 'MyLookup'
end

Alternative: table-less lookups and associations

TODO: probably won't work yet…at least need to add an _id attribute to the associating class.…

Other (FUTURE)

Some work is yet to be done to support general classes using acts_as_lookup

Configuration

acts_as_lookup accepts an options hash with one required key: :values, which is an array of hashes that contain lookup data (see above).

Other options available:

:sync_with_db

Fetches existing records from the db and merges them into the cached values (default true).

:write_to_db

Writes any missing values to the db (default true).

:add_query_methods

Defines query methods on instances of the lookup model for checking the identity of a value (default false). For example:

def Status < ActiveRecord::Base
  VALS = [ { :id => 1, :name => "active", },
           { :id => 2, :name => "disabled", }
         ]
  acts_as_lookup :values => VALS, :add_query_methods => true
end

Status.active.active? # => true
Status.active.disabled? # => false

Development

Testing

Run rake spec to run the (rspec) tests. You should add tests for anything you touch.