Last active
September 18, 2017 18:40
-
-
Save godfat/dbcdbe0ad5d79dbf1761 to your computer and use it in GitHub Desktop.
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
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