Sha256: c3193a2ae5619f39452185a8c9249c2c27dddb508a9395d6f5ee111d8fe91a73

Contents?: true

Size: 847 Bytes

Versions: 1

Compression:

Stored size: 847 Bytes

Contents

require "active_record_jsonb_with_indifferent_access/version"

module ActiveRecordJsonbWithIndifferentAccess
  def self.included base
    base.extend ClassMethods
  end

  module ClassMethods
    def json_columns_with_indifferent_access(*columns)
      columns.each { |column| serialize(column, JsonWithIndifferentAccessSerializer) }
    end
  end

  class JsonWithIndifferentAccessSerializer
    class UnsupportedDataType < StandardError; end;

    def self.load(obj)
      obj = JSON.load(str) if obj.is_a?(String)
      indifferent_access(obj)
    end

    def self.dump(obj)
      JSON.dump(obj)
    end

    private

    def self.indifferent_access(obj)
      obj ||= {}
      if obj.is_a?(Hash)
        obj.with_indifferent_access
      else
        raise UnsupportedDataType, "Expected data to be nil or a hash."
      end
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
active_record_jsonb_with_indifferent_access-0.1.0 lib/active_record_jsonb_with_indifferent_access.rb