-
Notifications
You must be signed in to change notification settings - Fork 9
JSON Aliases
An important difference between storing data in RDBMS columns and in JSON format is that, in JSON, the name of a field is stored for every instance of data stored in it. (In a relational database, it's stored only once, in the metadata for a table.)
As a result, there's a tension: if you use a long, descriptive field name, your code is much cleaner and easier to read, but you may end up wasting a very non-trivial amount of precious database buffer cache (and space on disk, albeit far less precious) storing many, many copies of that field name. If you use a very terse field name, you waste much less space, but your code is much harder to read.
flex_columns
solves this problem by letting you declare a JSON alias: your code, including autogenerated methods, hash-access syntax, and so on, will use the long, descriptive field name of your choosing. However, inside the JSON store, it will use the alias you give it, saving much space.
For example:
class User < ActiveRecord::Base
flex_column :user_attributes do
field :maximum_number_of_emails_desired_per_week, :json => :ewk
field :custom_background_color, :json => :cbc
end
end
You can then say:
my_user = User.new
my_user.maximum_number_of_emails_desired_per_week = 5
my_user.custom_background_color = :green
my_user.save!
and the JSON in that row's user_attributes
column will look like:
{"ewk":5,"cbc":"green"}
This is a very significant savings — from 81 bytes down to 23 bytes.
In case it's not obvious: changing a JSON alias will effectively remove all data in that field, because flex_columns
will be looking for a different field name. If you decide you want to change a field alias mid-stream, you can easily override its accessor method to look for data using the old name or the new name, and then return data (or even migrate it automatically when touched).