Sha256: a162ee9e4f3689f984d9424ad233d9f31739a62f8b0eb75451ad87cfba2ef676
Contents?: true
Size: 1.84 KB
Versions: 1
Compression:
Stored size: 1.84 KB
Contents
# frozen_string_literal: true module Idy module Extension extend ActiveSupport::Concern included do def idy self.class.idy_encode id end def salt self.class.salt end def to_param return super unless self.class.respond_to?(:idy?) self.class.idy_encode id end end module ClassMethods def find(*args) id = args.first return super if args.count != 1 || integer?(id) scope = try(:idy?) ? [id].flatten.map { |id| idy_decode(id) } : id not_found!(id) if scope.compact.blank? super scope.size == 1 ? scope[0] : scope end def findy(hash) find_by id: idy_decode(hash) end def findy!(hash) record = find_by(id: idy_decode(hash)) not_found!(hash) if record.nil? record end def idy(options = {}) @idy_options = options.reverse_merge(salt: idy_default_salt) define_singleton_method(:idy?) { true } end def idy_decode(hash, salt: self.salt) encoder(salt).decode(hash).first end def idy_default_salt alphabet = Array('a'..'z') indexes = name.downcase.split('').map do |char| alphabet.index(char) + 1 end indexes.shift(10).join end def idy_encode(id, salt: self.salt) return unless id encoder(salt).encode id end def idy_options @idy_options || { salt: idy_default_salt } end def salt idy_options[:salt] end private def encoder(salt) Hashids.new salt.to_s end def integer?(id) Integer id rescue false end def not_found!(hash) raise ActiveRecord::RecordNotFound, "Couldn't find User with 'idy'=#{hash.inspect}" end end end end
Version data entries
1 entries across 1 versions & 1 rubygems
Version | Path |
---|---|
idy-0.1.3 | lib/idy/extension.rb |