module Idy::Extension::ClassMethods

Public Instance Methods

findy(hash) click to toggle source
# File lib/idy/extension.rb, line 24
def findy(hash)
  find_by id: idy_decode(hash)
end
findy!(hash) click to toggle source
# File lib/idy/extension.rb, line 28
def findy!(hash)
  record = find_by(id: idy_decode(hash))

  not_found!(hash) if record.nil?

  record
end
idy(options = {}) click to toggle source
# File lib/idy/extension.rb, line 36
def idy(options = {})
  @idy_options = options.reverse_merge(salt: idy_default_salt)

  define_singleton_method(:idy?) { true }
end
idy_decode(hash, salt: self.salt) click to toggle source
# File lib/idy/extension.rb, line 42
def idy_decode(hash, salt: self.salt)
  encoder(salt).decode(hash).first
end
idy_default_salt() click to toggle source
# File lib/idy/extension.rb, line 46
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
idy_encode(id, salt: self.salt) click to toggle source
# File lib/idy/extension.rb, line 56
def idy_encode(id, salt: self.salt)
  return unless id

  encoder(salt).encode id
end
idy_options() click to toggle source
# File lib/idy/extension.rb, line 62
def idy_options
  @idy_options || { salt: idy_default_salt }
end
salt() click to toggle source
# File lib/idy/extension.rb, line 66
def salt
  idy_options[:salt]
end

Private Instance Methods

encoder(salt) click to toggle source
# File lib/idy/extension.rb, line 72
def encoder(salt)
  Hashids.new salt.to_s
end
not_found!(hash) click to toggle source
# File lib/idy/extension.rb, line 76
def not_found!(hash)
  raise ActiveRecord::RecordNotFound, "Couldn't find User with 'idy'=#{hash.inspect}"
end