Skip to content

Instantly share code, notes, and snippets.

@hfwang
Created April 10, 2012 18:01
Show Gist options
  • Save hfwang/2353284 to your computer and use it in GitHub Desktop.
Save hfwang/2353284 to your computer and use it in GitHub Desktop.
Use Ruby's marshal facilities in ActiveRecord to serialize some attributes for schema-less awesome.
class CreateModels < ActiveRecord::Migration
def change
create_table :models do |t|
t.binary :extras
t.timestamps
end
end
end
module MarshalStore
class NilFriendlyMarshal
def self.load(str)
if str.nil?
return Hash.new
else
Marshal.load(str) || Hash.new
end
end
def self.dump(str)
Marshal.dump(str)
end
end
extend ActiveSupport::Concern
module ClassMethods
def marshal_store(store_attribute, options={})
serialize(store_attribute, NilFriendlyMarshal)
store_accessor(store_attribute, options[:accessors]) if options.has_key? :accessors
end
end
end
class Model < ActiveRecord::Base
include MarshalStore
# Same API as regular ActiveRecord::Base.store
marshal_store :extras, :accessors => [:name, :description, :founder_id]
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment