Friday, 13 July 2012

axonflux- The rate of signal flow across long nerve fiber between neurons

One of my favorite additions to Rails 3 - ActiveRecord::Store - brings sexy back to old unsexy MySQL

One of the least favorite things I hated to do was migrate schema. Luckily Rails 3 has this new semantic called 'store' -- as detailed here
Store gives you a thin wrapper around serialize for the purpose of storing hashes in a single column. It's like a simple key/value store backed into your record when you don't care about being able to query that store outside the context of a single record.
You can then declare accessors to this store that are then accessible just like any other attribute of the model. This is very helpful for easily exposing store keys to a form or elsewhere that’s already built around just accessing attributes on the model.
Make sure that you declare the database column used for the serialized store as a text, so there’s plenty of room.
class User < ActiveRecord::Base
  store :settings, accessors: [ :color, :homepage ]

u = 'black', homepage: '')
u.color                          # Accessor stored attribute
u.settings[:country] = 'Denmark' # Any attribute, even if not specified with an accessor

# Add additional accessors to an existing store through store_accessor
class SuperUser < User
  store_accessor :settings, :privileges, :servants
I love this because now I can just store extra info at any time just by altering my model code. No more waiting for the next schema migration and all the pain of that on a production server. Just drop it into a serialized hash that's persisted into a TEXT blob on your row, and you're all good. NICE. 
Of course that doesn't solve the problem of needing to index something specific -- but you can always just add that in your next major schema revision anyway, and then fill in that column on an offline basis later. 
Back in 2010, Adam D'angelo speculated that NoSQL was mainly a fad that would end with a relational database with more relaxed semantics. Well, this is at least 50% of the way there, at the app level.
Hell, this is actually how FriendFeed would store data in MySQL back in the day -- JSON blobs, and they'd just create new tables when they needed new indices. No schema changes EVER with that approach. 
Little things like this make it difficult to impossible for me to consider using other web platforms than Rails -- other than years of my tooling about in it (and learning all kinds of lessons the hard way), things just keep getting better and better. 

No comments:

Post a Comment