Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Rails.application.config.after_initialize do
ActiveSupport.on_load(:active_record) do
oid = ActiveRecord::ConnectionAdapters::PostgreSQLAdapter::OID
# https://github.com/rails/rails/blob/v4.2.3/activerecord/lib/active_record/connection_adapters/postgresql/oid/jsonb.rb
oid::Jsonb = Class.new(oid::Json) do
def type
:jsonb
end
def changed_in_place?(raw_old_value, new_value)
# Postgres does not preserve insignificant whitespaces when
# round-tripping jsonb columns. This causes some false positives for
# the comparison here. Therefore, we need to parse and re-dump the
# raw value here to ensure the insignificant whitespaces are
# consistent with our encoder's output.
raw_old_value = serialize(deserialize(raw_old_value))
super(raw_old_value, new_value)
end
end
oid.alias_type('jsonb', oid::Jsonb)
# apply on models:
require 'sequel'
patch_model = lambda do
db = Sequel.connect(ENV['DATABASE_URL'])
db.select(:table_name, :column_name).
from(:information_schema__columns).
where(:data_type => 'jsonb',
:column_default => "'{}'::jsonb").all.each do |h|
Object.const_get(h[:table_name].classify).
serialize(h[:column_name], JSON)
end
end
patch_model.call
# fix rails auto-reloading
if Rails.configuration.cache_classes == false
ActionDispatch::Reloader.to_prepare(&patch_model)
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.