Serializing custom ActiveRecord attributes as JSON
I'm not a big fan of ActiveRecord's serialize. But I have kept it together until I learned about DataMapper's custom serializers for custom types. At that point, I was ready to cry. I was saved by the following inspiration.
I've been looking for a fast (no YAML) and framework agnostic (no classname stored) way to serialize a custom object into an ActiveRecord attribute. Here's my simple hack to create custom serializers in Rails using composed_of.
class User < ActiveRecord::Base
composed_of :settings, :class_name => 'Settings', :mapping => %w(settings to_json),
:constructor => Settings.method(:from_json),
:converter => Settings.method(:from_json)
after_validation do |u|
u.settings = u.settingsĀ if u.settings.dirty? # Force to serialize
end
endYes. It's that simple. To clarify, after_validation self-assignment is needed to make sure that if you edit the Settings object in-place, that it gets serialized into the attribute. Note: I've tried the user.settings_will_change! option and it didn't work -- it forces the save, but not the serialization.
Now you can get crazy like a fox (ie. FriendFeed) and store schema-less data via Rails.
