Created
April 10, 2012 18:01
-
-
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class CreateModels < ActiveRecord::Migration | |
def change | |
create_table :models do |t| | |
t.binary :extras | |
t.timestamps | |
end | |
end | |
end |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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