Skip to content

Instantly share code, notes, and snippets.

@zerobearing2
Last active December 27, 2015 00:59
Show Gist options
  • Select an option

  • Save zerobearing2/7242080 to your computer and use it in GitHub Desktop.

Select an option

Save zerobearing2/7242080 to your computer and use it in GitHub Desktop.
ActiveRecord Store for Postgres' JSON data type
module ActiveRecord
module PgJsonStore
extend ActiveSupport::Concern
module ClassMethods
#
# Store (JSON) using Postgres
# JSON data type.
#
# Inspired by: http://api.rubyonrails.org/classes/ActiveRecord/Store.html
#
# Example:
#
# class User < ActiveRecord::Base
# include ActiveRecord::PgJsonStore
#
# pg_json_store :address, accessors: [:street1,
# :street2, :city, :state, :postal, :country]
# end
#
# User.new(city: "San Diego", state: "CA")
# => #<User address: {"city"=>"San Diego", "state"=>"CA"}>
#
def pg_json_store(column, options = {})
column = column.to_sym
accessors = options.delete(:accessors)
store_accessor(column, accessors) if accessors
# # def address
# # read_attribute(:address) || Hash.new
# # end
# define_method("#{column}") do
# read_attribute(column) || Hash.new
# end
# [*accessors].each do |accessor|
# accessor = accessor.to_sym
# # def city
# # read_store_attribute(:address, 'city')
# # end
# define_method("#{accessor}") do
# read_store_attribute(column, accessor)
# end
# # def city=(val)
# # write_store_attribute(:address, 'city', val)
# # end
# define_method("#{accessor}=") do |val|
# write_store_attribute(column, accessor, val)
# end
# end
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment