Vertical Tables in Rails

I just released a rails plugin that provides a mix-in so a class can get it’s attributes from an associated vertical table.

So if you have a table called ‘preferences’ or something that your other developers are constantly stuffing key-value pairs into, then go ahead and use this muh to stop writing a bunch of accessors. It wraps around an existing association to provide DRY access to that table, in a way you’ll never have to think about again.

Something cool about this – It basically de-schemafies one of (or all of) your models. You COULD, though I don’t know why you’d want to, do something obscene like this:

#  no attributes, just an ID and Type column
class DbObject < ActiveRecord::Base
  has_many :db_attributes, :autosave => true
  include VerticalTable::Attributes
 
  def self.has_attributes(*attrs)
    vertical_attributes_from(:db_attributes) do |v|
      attrs.each do |a|
        v.send(a, :key => a)
      end
    end
  end
end
 
# id, db_object_id, key, value
class DbAttribute < ActiveRecord::Base
  belongs_to :db_object
end
 
  Person = Class.new(DbObject) do
    has_attributes :fname, :lname, :phone
  end
 
  should "allow me to use a person as if it had real attrs" do
    p = Person.create(:fname => "Alex", 
      :lname => "Bartlow", :phone => '8675309')
    assert_equal "Alex", p.fname
  end

So there you go. Schemaless MySQL. The scary thing is, you might be able to cluster/partition this by the db_object_id and it might actually be performant.

Head asplode and all.

Post a Comment

Your email is never published nor shared. Required fields are marked *

*
*