Skip to content

Instantly share code, notes, and snippets.

@bbugh
Created October 6, 2017 14:24
Show Gist options
  • Save bbugh/40472465ddcbfc6540180741a4b7b41c to your computer and use it in GitHub Desktop.
Save bbugh/40472465ddcbfc6540180741a4b7b41c to your computer and use it in GitHub Desktop.
IndifferentHashSerializer for Rails json/jsonb columns
# app/serializers/indifferent_hash_serializer.rb
# Used for converting a json or jsonb column into a useable Rails hash instead
# of the psuedo-json hash that is normally returned by Rails.
class IndifferentHashSerializer
def self.dump(hash)
hash.to_json
end
def self.load(hash)
return HashWithIndifferentAccess.new if hash.blank?
hash = JSON.parse(hash) if hash.is_a? String
hash.with_indifferent_access
end
end
# spec/serializers/indifferent_hash_serializer_spec.rb
require 'rails_helper'
describe IndifferentHashSerializer do
subject { described_class }
describe ".dump" do
it "converts the hash to json" do
hash = { test: true }
expect(subject.dump(hash)).to eq "{\"test\":true}"
end
end
describe ".load" do
context "when the data is a string" do
it "loads a hash with indifferent access" do
json = "{\"other_test\":\"some string\"}"
expect(subject.load(json)[:other_test]).to eq "some string"
end
end
context "when the data is a hash" do
it "returns the hash, indifferently" do
expect(subject.load("realtest" => "supreme")[:realtest]).to eq "supreme"
end
end
context "when the data is nil" do
it "returns an empty hash" do
expect(subject.load(nil)).to eq({})
end
end
end
end
class MyModel < ApplicationRecord
serialize :options, IndifferentHashSerializer
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment