Sha256: 434ac7fe7cfc90e04344cec3de6cc5be1f718561e43e5a80ec0d90b273407e65

Contents?: true

Size: 951 Bytes

Versions: 3

Compression:

Stored size: 951 Bytes

Contents

# frozen_string_literal: true

require 'active_record'
require 'active_support'

module Lite
  module Uxid
    module Record
      module Hash

        extend ActiveSupport::Concern

        included do
          after_create :callback_generate_uxid!, if: proc { respond_to?(:uxid) }
        end

        class_methods do
          def find_by_uxid(uxid)
            decoded_id = Lite::Uxid::Hash.decode(uxid)
            find_by(id: decoded_id)
          end

          def find_by_uxid!(uxid)
            record = find_by_uxid(uxid)
            return record unless record.nil?

            raise ActiveRecord::RecordNotFound
          end
        end

        def uxid_to_id
          return unless respond_to?(:uxid)

          Lite::Uxid::Hash.decode(uxid)
        end

        private

        def callback_generate_uxid!
          hash = Lite::Uxid::Hash.encode(id)
          update_column(:uxid, hash)
        end

      end
    end
  end
end

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
lite-uxid-1.0.5 lib/lite/uxid/record/hash.rb
lite-uxid-1.0.4 lib/lite/uxid/record/hash.rb
lite-uxid-1.0.3 lib/lite/uxid/record/hash.rb