Sha256: 7efd756988dedd77e47c5547e933d7507c2115cf8e3ce6adbfdffc0161235717

Contents?: true

Size: 976 Bytes

Versions: 1

Compression:

Stored size: 976 Bytes

Contents

# frozen_string_literal: true

require 'active_support' unless defined?(ActiveSupport)

module Lite
  module Uxid
    module Record
      module Hashid

        extend ActiveSupport::Concern

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

        class_methods do
          def find_by_uxid(uxid)
            decoded_id = Lite::Uxid::Hashid.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::Hashid.decode(uxid)
        end

        private

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

      end
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
lite-uxid-1.1.3 lib/lite/uxid/record/hashid.rb