Skip to content

Instantly share code, notes, and snippets.

@edbond
Forked from godfat/rails41_jsonb.rb
Created September 18, 2017 18:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save edbond/53a7b52497f0aba4ed25d4ea70160ec4 to your computer and use it in GitHub Desktop.
Save edbond/53a7b52497f0aba4ed25d4ea70160ec4 to your computer and use it in GitHub Desktop.
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