Vertical Tables in Rails
March 20th 2010I 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
has_many :db_attributes, :autosave => true
include VerticalTable::Attributes
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
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.