Created
September 3, 2023 22:03
-
-
Save javierav/f8ecc508900f3cb9f6d3f0a88f666a4d to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
module Sqidsable | |
extend ActiveSupport::Concern | |
module ClassMethods | |
def find(*ids) | |
expects_array = ids.first.is_a?(Array) | |
uniq_ids = ids.flatten.compact.uniq | |
uniq_ids = uniq_ids.first unless expects_array || uniq_ids.size > 1 | |
super(sqids_decode(uniq_ids)) | |
end | |
def find_by_sqid(sqid) | |
find_by(id: sqids_decode(sqid)) | |
end | |
def find_by_sqid!(sqid) | |
find_by!(id: sqids_decode(sqid)) # rubocop:disable Rails/FindById | |
end | |
def sqids_decode(ids) | |
if ids.is_a?(Array) | |
ids.map { |id| sqids.decode(id).first } | |
else | |
sqids.decode(ids).first | |
end | |
end | |
def sqids_encode(ids) | |
if ids.is_a?(Array) | |
ids.map { |id| sqids.encode(Array.wrap(id)) } | |
else | |
sqids.encode(Array.wrap(ids)) | |
end | |
end | |
def relation | |
super.tap { |r| r.extend ClassMethods } | |
end | |
def has_many(*args, &) # rubocop:disable Naming/PredicateName | |
options = args.extract_options! | |
options[:extend] = Array(options[:extend]).push(ClassMethods) | |
super(*args, **options, &) | |
end | |
private | |
def sqids | |
@sqids ||= Sqids.new | |
end | |
end | |
def sqid | |
self.class.sqids_encode(id) | |
end | |
def to_param | |
sqid | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment