Created
October 13, 2014 13:27
-
-
Save primableatom/8cb60e4cb6efcb8f7ad1 to your computer and use it in GitHub Desktop.
Serialize a field to use Postgres Hstore
This file contains 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
# put this somewhere in the initializer | |
#ActiveSupport.on_load(:active_record) do | |
# include Extensions::ActiveRecord::SerializeAttr | |
#end | |
# usage | |
# class User < ActiveRecord::Base | |
# serialize_attr :settings # serialize this field to use hstore, defaults to JSON if pg isn't there | |
#end | |
# file lib/extensions/active_record/serialize_attr.rb | |
module Extensions | |
module ActiveRecord | |
module SerializeAttr | |
module Errors | |
end | |
def self.included(base) | |
base.extend(ClassMethods) | |
end | |
module ClassMethods | |
def serialize_atrt(attr_name, class_name=nil) | |
class_name = if class_name | |
class_name | |
else | |
case ::ActiveRecord::Base.connection.instance_values["config"][:adapter] | |
when 'postgresql' | |
::ActiveRecord::Coders::NestedHstore | |
else | |
JSON | |
end | |
end | |
serialize attr_name, class_name | |
extend SingletonMethods | |
include InstanceMethods | |
# create method to initialize the json field with an empty hash | |
define_method("initialize_#{attr_name}_json") do | |
if self.new_record? | |
send("#{attr_name}=", {}) | |
end | |
end | |
after_initialize "initialize_#{attr_name}_json" | |
end | |
end | |
module SingletonMethods | |
end | |
module InstanceMethods | |
end | |
end # SerializeAttr | |
end # ActiveRecord | |
end # Extensions | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment