Sha256: 32f03b986c437891da38457ba236970049ebb22698bcd46a8aa3cfc7bb63c9c8

Contents?: true

Size: 1.14 KB

Versions: 2

Compression:

Stored size: 1.14 KB

Contents

# frozen_string_literal: true

require 'active_record'

require 'active_serialize/version'
require 'active_serialize/class_methods'

module ActiveSerialize
  extend ActiveSupport::Concern
  cattr_accessor :configs, default: { default: { rmv: [ ], add: [ ] } }

  class_methods do
    def active_serialize rmv: [ ], add: [ ], recursive: [ ]
      extend   ClassMethods
      include  ToH
      delegate :active_serialize_keys, :_active_serialize, to: self

      active_serialize_rmv *Array(rmv)
      active_serialize_add *Array(add)
      active_serialize_add *Array(recursive), recursive: true
    end

    def active_serialize_default **args
      ActiveSerialize.configs[:default].merge!(args)
    end
  end

  module ToH
    def to_h(rmv: [ ], add: [ ], merge: { })
      tran_key = ->(key) { (_active_serialize[:map][key] || key).to_s }
      recursion = _active_serialize[:recursive].map { |key| [ tran_key.(key), public_send(key)&.to_ha ] }.to_h
      active_serialize_keys(rmv: rmv, add: add)
          .map{ |key| [ tran_key.(key), public_send(key) ] }.to_h
          .merge(merge).merge(recursion)
    end
  end
end

ActiveRecord::Base.include ActiveSerialize

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
active_serialize-2.1.0 lib/active_serialize.rb
active_serialize-2.0.2 lib/active_serialize.rb